/* eslint-disable */
import wx from 'weixin-js-sdk'
import store from '../store/index.js'
import { reportPageShareSuccess } from "@/utils/userTraceLog.js";
import { LOAD_STATUS_ENUM } from '@/utils/constant.js'
import { ckjrRequest } from '@/utils/http.js';
const curUa = navigator.userAgent.toLowerCase();
const deviceUtil = (()=>{
  // 是否ios设备，包括手机，电脑，ipad
  const isIos = /iphone|ipad|ipod|macintosh|mac os x|mac os/.test(curUa);
  const isWeixin = /micromessenger/i.test(curUa);
  return {
    isIos,
    isWeixin
  }
})()

console.log('--deviceUtil--',deviceUtil)
let qr = null;
if (!deviceUtil.isWeixin || !(/iphone|ipad|ipod|android|android.*mobile|windows.*phone|blackberry.*mobile/i.test(curUa))) {
  import('../utils/qr.js').then(res => {
    qr = res.default;
  });
}
import { checkApiHp } from '../utils/apihpCheck';
var utilJs = {
  /**
   * 根据url获取当前公司id同时设置门店id
   * @param {*} href 
   * @returns 
   */
  getCompanyIdByHerf(href){
    const curUrl = href || window.location.href;
    const cId = curUrl.split("/")[4];
    if(!cId){
      return '';
    }
    const companyId = cId.split("-")[0]
    return companyId;
  },
  setStoreId(href){
    const curUrl = href || window.location.href;
    const cId = curUrl.split("/")[4];
    if(!cId){
      return '';
    }
    //获取设置门店id
    const cIdArr = cId.split("-");
    let storeId = '';
    if(cIdArr.length > 1){
      storeId = cIdArr[1];
    } 
    //如果本地缓存的门店id和当前获取的门店id不一致 && 存在登录的token，则需要清楚缓存重新授权
    if(utilJs.getStoreId() != storeId && localStorage.getItem('token')){
      utilJs.clearLocalStorage();
    }
    localStorage.setItem('X-STORE-ID', storeId);
  },
  /**
   * 获取门店id
   */
  getStoreId(){
    return localStorage.getItem('X-STORE-ID') || '';
  },
  /**
   * 清除全部本地缓存
   */
  clearLocalStorage(){
    if ((navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1) && window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger' && localStorage.getItem("companyId")) {
      // 把之前的cookie设置过期，防止cookie不停地增加导致http request 400错误
      let exp = new Date();
      exp.setTime(exp.getTime() - 1);
      document.cookie = localStorage.getItem("companyId") + "|token=;expires=" + exp.toGMTString() + ";path=/";
    }
    window.localStorage.clear();
  },

  /**
   * 获取来源应用的值
   *  CHANNEL_H5 = 1; // 公众号
      CHANNEL_H5_WXAPP = 2; // 小程序
      CHANNEL_H5_APP = 3; // 客户APP
      CHANNEL_H5_PC = 4; // PC端
      CHANNEL_PLATFORM_WXAPP = 5; // 创客匠人小程序
      CHANNEL_PLATFORM_APP = 6; // 创客匠人学员版APP
      CHANNEL_PLATFORM_WXAPP_LIVE = 7; // 创匠直播小程序
      CHANNEL_PLATFORM_WXAPP_SIGNCARD = 8; // 创匠打卡小程序
      CHANNEL_UNKNOWN = -1; // 未知渠道
   * @returns {number} 渠道来源的值
   */
  getFromApplicationNum(){
    const APPLICATION_ENUM = {
      'CHANNEL_H5':1,
      'CHANNEL_H5_WXAPP':2,
      'CHANNEL_H5_APP':3,
      'CHANNEL_H5_PC':4,
      'CHANNEL_PLATFORM_WXAPP':5,
      'CHANNEL_PLATFORM_APP':6,
      'CHANNEL_PLATFORM_WXAPP_LIVE':7,
      'CHANNEL_PLATFORM_WXAPP_SIGNCARD':8,
      'CHANNEL_UNKNOWN':-1,
    }
    //app套壳
    if(utilJs.isIOSAppALL() || utilJs.isAndroidApp()){
      return APPLICATION_ENUM.CHANNEL_H5_APP;
    }
    //套壳小程序 区分履约小程序和客户套壳小程序
    if(utilJs.checkWxApp()){
      return sessionStorage.getItem('isKpStudy') == 1 ? APPLICATION_ENUM.CHANNEL_PLATFORM_WXAPP : APPLICATION_ENUM.CHANNEL_H5_WXAPP;
    }
    return APPLICATION_ENUM.CHANNEL_H5;
  },
    /**
   * 将文本复制到剪贴板。
   *
   * @param {string} text - 要复制的文本内容。
   * @param {number} showSuccessText - 是否显示复制成提示 1 显示 0 不显示
   * @returns {Promise<void>} - 返回一个 Promise，成功时解析为 undefined，失败时拒绝。
   * @throws {Error} - 如果文本为空或浏览器不支持剪贴板 API，则抛出错误。
   * @example
   * copyText('Hello, World!')
   *   .then(() => {
   *     console.log('文本已成功复制到剪贴板');
   *   })
   *   .catch((error) => {
   *     console.error('复制文本时出错:', error);
   *   });
   */
  copyText(text,showSuccessText = 1) {
    const handleError = (message) => {
      Vue.prototype.$showCjToast({
        text: message,
        type: 'warn',
      });
      return Promise.reject(message);
    };
    if (!text) {
      return handleError('请选择复制的内容');
    }
    if(utilJs.isAndroidApp() || utilJs.isIOSAppALL()){
      return utilJs.oldCopyText(text,showSuccessText);
    }
    if (!navigator.clipboard) {
      return handleError('当前浏览器不支持复制');
    }
    return navigator.clipboard
      .writeText(text)
      .then(() => {
        showSuccessText == 1 && Vue.prototype.$showCjToast({
          text: '复制成功',
          type: 'success',
        });
      })
      .catch(() => {
        //复制失败，尝试使用旧版本复制接口
        return utilJs.oldCopyText(text,showSuccessText);
      });
  },
  oldCopyText(text,showSuccessText) {
    return new Promise((resolve, reject) => {
      const handleError = (message) => {
        Vue.prototype.$showCjToast({
          text: message,
          type: 'warn',
        });
         // 移除文本区域元素
         document.body.removeChild(textarea);
        return reject(message);
      };
      // 创建一个文本区域元素
      const textarea = document.createElement("textarea");
      // 设置文本内容
      textarea.value = text;
      // 防止滚动条出现
      textarea.style.position = "fixed";
      textarea.style.opacity = "0";
      // 将文本区域添加到文档中
      document.body.appendChild(textarea);
      // 选中文本区域的内容
      textarea.select();
      // 执行复制操作
      try {
          const successful = document.execCommand("copy");
          console.log('test-successful',successful)
          if(successful){
            showSuccessText == 1 && Vue.prototype.$showCjToast({
              text: '复制成功',
              type: 'success',
            });
            // 移除文本区域元素
            document.body.removeChild(textarea);
            return resolve();
          }else{
            handleError('复制失败');
          }
      } catch (err) {
        handleError('复制失败');
      }
      
    })
  },
  /**
   * 调起本地文件选择器
   * @param {Object} opt 
   * @param {String} opt.accept 文件选择限制类型
   * @param {Boolean} opt.multiple 是否多选
   * @param {Boolean} opt.max 最多可选文件数量，超过的话自动丢弃多余的
   * @returns {Promise<File[]>} file文件数组
   */
  chooseLocalFile(opt = {}){
    const DEFAULT_OPTIONS = {
      accept:'image/*', //文件选择类型
      multiple: false, //是否多选
      max: 9, //默认一次最多只能选9张图
      inputDomId:'chooseLocalInputFile'
    };
    const options = {...DEFAULT_OPTIONS,...opt};
    return new Promise((resolve,reject)=>{
      //文件选中事件回调
      const handerInputChange = (event)=>{
        let file = event.target.files;
        //文件内容为空
        if(!file.length){
          return reject();
        }

        if(file.length > options.max){
          file = Array.from(file).slice(0,options.max);
        }
        resolve(file)
      };
      let fileDom = document.getElementById(options.inputDomId);
      //如果body上没有input，需要手动添加一次
      if(!fileDom){
        fileDom = document.createElement("input");
        fileDom.type = 'file';
        fileDom.style = `opacity:0;position:fixed;left:-999px;top:0;z-index:-999`;
        fileDom.id = options.inputDomId;
        document.body.appendChild(fileDom);
      }

      fileDom.accept  = options.accept;
      fileDom.multiple = options.multiple;
      fileDom.value = '';
      fileDom.onchange = handerInputChange;
      fileDom.click();
    });
  },
  /**
   * 获取阿里云oss签名
   * @returns 
   */
  getAliYunSign(){
    return new Promise((resolve,reject)=>{
      utilJs.getMethod(`${global.apiurl}imageSign`, res=>{
        const aliYunSign = {
          'key': res.dir,
          'policy': res.policy,
          'OSSAccessKeyId': res.accessid,
          'success_action_status': '200',
          'callback': res.callback,
          'signature': res.signature,
          'aliYunHost': res.host
        }
        resolve(aliYunSign)
      },()=>{
        reject('获取签名失败');
      })
    });
  },
  /**
   * 将图片上传到oss,内部方法，外部不要使用
   * @param {File} file 文件对象
   * @param {Object} options 上传到oss的参数
   * @param {String} options.moduleName  上传图片的模块名称
   * @param {Object} options.signInfo  上传oss签名信息，如果有就不去获取,多次上传的时候防止每次都去获取签名信息
   * @returns {String} url 图片访问地址
   */
  async _uploadImgToOss(file,options = {}){
      const aliYunSign =  options.signInfo;
      let companyId = localStorage.getItem('companyId');
      const name = file.name;
      let fileName = `mp_${companyId}_${name}`;
      //文件访问路径 = 域名+目录+时间戳+mp+模块名称+文件名称
      let fileKey = `${aliYunSign.key}${Date.now()}_mp_${options.moduleName}_${name}`;
      let formData = new FormData();
      formData.append("key", fileKey);
      formData.append("policy", aliYunSign.policy);
      formData.append("OSSAccessKeyId", aliYunSign.OSSAccessKeyId);
      formData.append("success_action_status", aliYunSign.success_action_status);
      formData.append("callback", aliYunSign.callback);
      formData.append("signature", aliYunSign.signature);
      formData.append("name", fileName);
      formData.append("file", file);
      const res = await ckjrRequest({
        method: 'post',
        headers: {"Content-Type":"multipart/form-data"},
        url: aliYunSign.aliYunHost,
        data: formData,
      })
      //啊里云返回格式Status=ok代表上传成功
      if(res.data.data && res.data.data.Status == 'Ok' && res.data.data.url){
        return res.data.data.url + '?x-oss-process=image/format,png';
      } else {
        return Promise.reject('图片上传失败')
      }
  },
  /**
   * 将图片列表上传到oss
   * @param {File} file 文件对象
   * @param {Object} opt 上传到oss的参数
   * @param {String} opt.moduleName  上传图片的模块名称
   * @param {String} opt.showLoading  是否显示loading提示
   * @param {Object} opt.signInfo  上传oss签名信息，如果有就不去获取,多次上传的时候防止每次都去获取签名信息
   * @returns {String} url 图片访问地址
   */
  async uploadImgListToOss(fileList,opt = {}){
    console.log('fileList',fileList)
    if(!fileList){
      return Promise.reject();
    }
    if(!fileList.length){
      return Promise.reject();
    }
    const DEFAULT_OPTIONS = {
      moduleName:'commmon',
      showLoading: true,
      signInfo: null,
    }
    const options = {...DEFAULT_OPTIONS,...opt}
    if(options.showLoading){
      Vue.prototype.$loading.show({
        text: '上传中...'
      });
    }
    try {
      //获取阿里云签名
      let aliYunSign;
      if(options.signInfo){
        aliYunSign = options.signInfo;
      }
      aliYunSign = await utilJs.getAliYunSign();
      const uploadList = [];
      for (let i = 0 ; i < fileList.length ; i++) {
        uploadList.push(utilJs._uploadImgToOss(fileList[i], {moduleName: options.moduleName, signInfo: aliYunSign}));
      }
      const imgList =  await Promise.all(uploadList);
      return imgList;
    } catch (error) {
      Vue.prototype.$showCjToast({
        text: '图片上传失败',
        type: 'warn',
      });
      const errorData = {
        res: JSON.stringify(error),
        type: 'uploadImgListToOss',
      }
      utilJs.reprotError(errorData);
      throw error;
    } finally {
      //上传结束不管成功还是失败都关闭弹窗
      options.showLoading && Vue.prototype.$loading.hide();
    }
  },
  getUrlRoutePath(url){
    let urlPathArr = url.split('#');
    if(urlPathArr.length < 2){
      return '/';
    }
    let curUrl = urlPathArr[1];
    let curPath = curUrl.split('?')[0];
    return curPath;
  },
  parseUrlQueryParams(url) {
    const queryArr = url.split('?');
    
    if (queryArr.length < 2) {
      // 如果URL中没有查询参数，返回空对象
      return {};
    }
    
    const paramPairs = queryArr[queryArr.length - 1];
    if(paramPairs.indexOf('=') === -1){
      return {};
    }

      // 使用&分割查询参数对
    const paramArr = paramPairs.split('&');
    const paramsObj = {};
    for (const pair of paramArr) {
      // 对每个参数对，使用=分割键和值
      const [key, value] = pair.split('=');
      // URL解码键和值，因为它们在URL中可能是编码过的
      const decodedKey = decodeURIComponent(key);
      let decodedValue = decodeURIComponent(value);
       paramsObj[decodedKey] = decodedValue;
    }
    return paramsObj;
  },

  /**
   * 根据当前分页加载情况设置当前列表的数据和加载状态
   * 注意：LOAD_STATUS_ENUM对应的值是否和页面数据所需要的load状态值一致
   * @param {number} pageNo 当前页数
   * @param {number} pageSize 每页显示数量
   * @param {Array} newList 列表新数据
   * @param {Array} oldList 列表旧数据
   * @returns {resInfo:{list:合并后的列表数据,loadStatus:加载状态}} 列表数据以及加载状态
   */
  formatListData(pageNo,pageSize,newList,oldList){
    let resInfo = {
      list: [],
      loadStatus: LOAD_STATUS_ENUM.NO_DATA,
      page: 1,
    }
     //如果当前是第一页 && 新数据返回空---表示整个列表为空
     if (pageNo == 1 && newList.length == 0) {
      return resInfo;
    }
     //如果当前是第一页 ---不用管旧数据，直接返回第一页的数据
     if (pageNo == 1) {
      resInfo.list = newList;
    }
    //如果不是是第一页 --- 将新旧数据拼接起来
    if (pageNo > 1) {
      resInfo.list = [...oldList, ...newList];
    }
    //新数据数量小于size --- 没有下一页
    if (newList.length < pageSize) {
      resInfo.loadStatus = LOAD_STATUS_ENUM.NO_MORE_DATA;
    }
    //新数据数量等于size --- 还有下一页
    if (newList.length >= pageSize) {
      resInfo.loadStatus = LOAD_STATUS_ENUM.HAS_MORE_DATA;
      resInfo.page = pageNo + 1;
    }    
    return resInfo;
  },
  
  /**
   * 价格样式分割
   * @param {*} price 传入的价格
   * @param {*} smallClass 小数点后面价格数值的样式
   * @returns 
   */
  priceStyleChange(price, smallClass) {
    if (price == 0) { //实际付款价格允许显示0.00
      price = '0.00'
    } else {
      price = (price * 1 + 0.00000001).toFixed(2); // 防止字段传number型数据
    }
    if ((price * 1) == 0) {
      return price;
    }
    let splitPrice = (price.toString().replace(/-/g, '')).split('.')
    let afterPrice = `${splitPrice[0]}.<span class="${smallClass}">${splitPrice[1]}</span>`;
    return afterPrice;
  },

  /**
   * 
   * @param {Object} priceInfo 活动价格信息
   * @param {String | Number} priceInfo.price 活动价格
   * @param {Number} priceInfo.payType 活动支付类型
   * @param {Number} priceInfo.showType 活动价格显示样式 1显示为xxxx~xxxx 2显示为xxxx起
   * @returns {Object} {price:价格,isText:是否是文字,beforeSymbol:价格前符号,afterSymbol:价格后符号}
   */
  formatActivityPrice(priceInfo){
    const {price,payType,showType} = priceInfo;
    if(payType == 1){
      return {price:'免费', isText:1};
    }
    if(payType == 5){
      return {price:'购买指定课程参与', isText:1};
    }
    if(payType == 6){
      return {price:'指定用户参与', isText:1};
    }
    if(!price  || Number(price)== 0){
      return  {price:'免费', isText:1};
    }
    if(showType == 2 && `${price}`.split('~').length > 1){
      return {price:`${price}`.split('~')[0], afterSymbol:'起'};
    }
    if(showType == 1 && `${price}`.split('~').length > 1){
      return {beforeSymbol:'￥', price:`${price}`};
    }
    return {beforeSymbol:'￥',price:price,}
  },
  
  /**
   * 判断当前路劲是否需要微信授权，检验token
   */
  checkNoNeedAuth(path){
    //资料下载页
    if(path.includes('datumDownload')){
      return true;
    }
    //店铺认证结果页
    if(path.includes('shopAuthResult')){
      return true;
    }
    //清缓存页
    if(path.includes('clearLocalStorage')){
      return true;
    }
    //用户协议页
    if(path.includes('protocolInfo')){
      return true;
    }
    //支付测试页
    if(window.location.href.includes('payTest')){
      return true;
    }
    //iosapp手机号登陆页
    if(window.location.href.includes('iosBindMobile')){
      return true;
    }
    //支付宝支付中间页
    if(path.includes('homePage/course/aliPayMiddlePage') && window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) != 'micromessenger'){
      return true
    }
    return false;
  },
  deepCopy(str){
    if(!str){
      return str;
    }
    let copyStr = JSON.parse(JSON.stringify(str));
    return copyStr;
  },
  // 店铺已打烊提示
  alertShopExpire(el, expireTime) {
    let showExpire = expireTime - new Date().getTime() < 0;
    if (showExpire) {
      let isExireTime = new Date().getTime() - expireTime > 7776000000; // 过期时间超过3个月
      Vue.prototype.$cjConfirm({
        title: '店铺已打烊',
        message: `打烊期间无法购买商品，${isExireTime ? '无法访问!' : '所有服务停止!'}`,
        showCancelButton: false,
        clickCloseModal: false
      })
      return true;
    }
    return false;
  },
  //绑定手机号变成弹窗
  goBindMobile(queryData) {
    //如果是游客模式下还是正常走绑定手机号的页面，否者走弹窗绑定手机号
    if (!(localStorage.getItem("uMobile") && localStorage.getItem("uMobile") != undefined)) {
      if (localStorage.getItem("isVisitor") && !!utilJs.getMobileBrowserType() && utilJs.getMobileBrowserType() != 'wx') {
        // 防止走多遍login/bindMobile，导致绑手机注册后，回退还是在绑手机页面
        if (window.location.href.includes('homePage/login/bindMobile')) {
          return;
        }
        // 防止有些页面调用方法时，没有传推荐人id，导致关系链断掉
        let reIdArr = window.location.href.split('refereeId=');
        let rId = '';
        if (reIdArr.length > 1 && reIdArr[1]) {
          rId = reIdArr[1].split('&').length > 0 ? reIdArr[1].split('&')[0] : reIdArr[1];
          queryData = queryData ? {...queryData, ...{refereeId: rId}} : {refereeId: rId}
        }
        let moreUrl = ''
        if (queryData) {
          for (let key in queryData) {
            moreUrl += (moreUrl ? '&' : '?') + (key + '=' + queryData[key])
          }
        }
        window.location.href = window.location.href.split("#")[0] + "#/homePage/login/bindMobile" + moreUrl
      } else {
        store.commit("updateShowBindPhoneModal", {
          showBindPhoneModal: true
        });
      }
      return true;
    } else {
      return false;
    }
  },
  // 监听页面关闭，销毁实列
  destroyVuePage(vm) {
    // let isIosPhone = navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    // if (isIosPhone) {
    //   window.addEventListener('pagehide', e => {
    //     vm.$destroy();
    //     e.preventDefault();
    //   });
    // } else {
    //   window.addEventListener('beforeunload', e => {
    //     vm.$destroy();
    //     e.preventDefault();
    //   });
    // }
  },
  /**
   * 将任意名称转成除第一个字符以外全部替换成* 比如老鹰抓小鸡=>老**
   * @param {昵称} name 
   * @returns 
   */
  hiddenUserName(name = '',role = 1){
    if(role != 1){
      return name;
    }
    let str = name.replace(/^(.{3})(.+)/,'$1***');
    return str;
  },
  isOpenPcGuard(){
    let localStorageCfg = localStorage.getItem("cfg");
    let cfg = localStorageCfg && JSON.parse(localStorageCfg);
    let isDouyin = !!navigator.userAgent.includes('aweme'); // 判断是否是抖音浏览器
    //非微信 && PC以及非微信浏览器 && 非抖音 && 开启pc防盗链 && 非创客匠人的app
    if (!this.isWeiXin() && !isDouyin && cfg.enablePCGuard == 1 && !this.isAndroidApp() && !this.isAndoridNewApp() && !this.isIOSAppALL()) {
      return true;
    }
    return false;
  },
  //视频不全屏播放
  /*videoAttributeSet(vObj, isMarque = false) {
    let u = navigator.userAgent;
    let isAnd = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;//andrio终端
    if (isAnd && isMarque) {
      vObj.setAttribute("x5-video-player-type", "h5-page");
    }
    vObj.setAttribute("webkit-playsinline", " ");
    vObj.setAttribute("playsinline", " ");
    vObj.setAttribute("x5-playsinline", " ");
    vObj.removeAttribute("x-webkit-airplay");
    vObj.setAttribute("disablePictureInPicture", true);
    vObj.setAttribute("controlslist", "nodownload noremoteplayback");
    vObj.oncontextmenu = function () {
      return false;
    }
  },*/
  //跳转到csdpt2及目录项目
  goPage(vm, path, querys, type = 2) { //type： 0replace到本地 1.push本项目，2 href跳转到csdpt主项目,3是replace到csdpt主项目
    let queryStr = "";
    let toPath = "";
    if (querys && querys.length > 0) {
      for (let key in querys) {
        queryStr += key + "=" + querys[key] + '&';
      }
    }
    if (type == 1 || type == 0) {
      toPath = `${path}${queryStr ? '?' + queryStr.substring(0, queryStr.length - 1) : ''}`;
    } else {
      toPath = `https://${window.location.host}/csdpt/${window.location.href.split("/")[4]}/?#${path}${queryStr ? '?' + queryStr.substring(0, queryStr.length - 1) : ''}`;
    }
    if (utilJs.isIOSApp()) {
      if (type == 1 || type == 0) {
        window.webkit.messageHandlers.iosWechatRoute.postMessage(toPath);
      } else {
        let data = {
          path: toPath,
          type: "csdpt"
        }
        window.webkit.messageHandlers.iosWechatRoute.postMessage(JSON.stringify(data));
      }
    } else if (utilJs.isAndoridNewApp()) {
      let data = {
        path: toPath,
        type: type == 1 || type == 0 ? "": "csdpt"
      }
      window.androidWechatRoute.doAction(JSON.stringify(data))
    } else {
      if (type == 1 || type == 0) {
        vm.$routerGo(vm, type == 1 ? "push" : "replace", { path: toPath });
      } else {
        this.locationHref(toPath, vm, type == 3 ? 'replace' : 'href');
      }
    }
  },
  //音频的播放
  audioPlayFun: (audioObj, funType = 'play') => {
    //funType: play, load, ...
    if (!audioObj || audioObj == null || audioObj == "" || audioObj == undefined) {
      return;
    }
    //针对不同手机解决兼容性的问题
    if (utilJs.isWeiXin()) {
      try {
        if (funType == "load") {
          console.log('---------isWeiXin--audioObj---load');
          audioObj.load();
        } else {
          console.log('---------isWeiXin--audioObj---play');
          audioObj.play();
        }
        document.addEventListener("WeixinJSBridgeReady", function () {
          if (funType == "load") {
            console.log('---------WeixinJSBridgeReady--funType---load');
            audioObj.load();
          } else {
            console.log('--------WeixinJSBridgeReady---funType---play');
            audioObj.play();
          }
        }, false);
        WeixinJSBridge.invoke("getNetworkType", {}, function (e) {// eslint-disable-line
          // 在这里拿到 e.err_msg, 这里面就包含了所有的网络类型
          if (funType == "load") {
            console.log('---------getNetworkType--audioObj---load');
            audioObj.load();
          } else {
            console.log('---------getNetworkType--audioObj---play');
            audioObj.play();
          }
        });
      } catch (error) {
        console.log("WeixinJSBridge不兼容");
      }
      //解决iOS以及一些安卓手机不能自动播放的问题
      if (utilJs.isIosWechat() && (window.navigator.userAgent.toLowerCase().indexOf("12_") > -1)) {
        wx.ready(() => {
          if (funType == "load") {
            audioObj.load();
          } else {
            audioObj.play();
          }
        });
      }
    } else {
      if (funType == "load") {
        audioObj.load();
      } else {
        audioObj.play();
      }
    }
  },
  //跳转外链时防止新页面没有在顶部
  locationHref: (url, vm, type = 'href') => {
    if (!url) return
    // 处理小程序套壳环境的 微页面 自定义关于h5链接跳转没设置白名单的问题
    if (((url.indexOf('wx.ckjr001.com/kpv2p') > -1) || (url.indexOf('kptest.ckjr001.com') > -1) || (url.indexOf('wxapph5.ckjr001.com') > -1)) && localStorage.getItem('isWxApp') && localStorage.getItem('isWxApp') == 1) {
      // url = `https://wxapph5.ckjr001.com/mini${url.split('kpv2p')[1]}`;
      Vue.prototype.$routerGo(vm, "push", { path: url.split("#")[1] });
      return
    }
    if (type == 'replace') {
      window.location.replace(url);
    } else {
      window.location.href = url;
    }
    setTimeout(() => {
      window.scrollTo(0, 0);
    });
  },
  //获取渐变颜色
  getRgbStr: (themeValue, tabColorRGB, opacityValue, deg) => {
    let rgbStr = global.THEME_RGB_MAP[themeValue] || '255, 113, 0';
    if (tabColorRGB) {
      rgbStr = tabColorRGB;
    } else if (themeValue.includes('mb7') || themeValue.includes('mb8')) {
      let color = localStorage.getItem('mb7ThemeColor') || '#ff8831';
      rgbStr = utilJs.hexToRgb(color);
    }
    let str = !deg ? 'background:linear-gradient(90deg,rgba(' + rgbStr + ',1) 0%,rgba(' + rgbStr + ',' + opacityValue + ') 100%)' : 'background:linear-gradient(' + deg + 'deg,rgba(' + rgbStr + ',1) 0%,rgba(' + rgbStr + ',' + opacityValue + ') 100%)';
    return str;
  },
  /**
   * 
   * @param {array} listData 列表数据
   * 
   */
  checkNeedInitData: (listData) => {
    let scrollTop = document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
    let clientHeight = document.body.clientHeight && document.documentElement.clientHeight ? Math.min(document.body.clientHeight, document.documentElement.clientHeight) : Math.max(document.body.clientHeight, document.documentElement.clientHeight);
    let scrollHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
    //列表数据为空 || 当前页数为第一页 的时候初始化数据
    if (!((scrollTop + clientHeight < scrollHeight) && listData && listData.length > 0)) {
      return true;
    }
    return false;
  },
  //下拉到底部加载更多
  handleLoading: (callBack) => {
    let scrollTop = document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
    let clientHeight = document.body.clientHeight && document.documentElement.clientHeight ? Math.min(document.body.clientHeight, document.documentElement.clientHeight) : Math.max(document.body.clientHeight, document.documentElement.clientHeight);
    let scrollHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);

    if (scrollTop + clientHeight >= (scrollHeight - 20)) {
      callBack();
    }
  },
  // 指定窗口滚动加载更多
  elementLoading: (element, callback) => {
    let scrollTop = element.scrollTop;
    let clientHeight = element.clientHeight;
    let scrollHeight = element.scrollHeight;
    if (scrollTop + clientHeight >= (scrollHeight - 20)) {
      callback();
    }
  },
  //异步加载JS
  syncLoadJs(jsPath) {
    let that = this;
    return new Promise(function (resolve, reject) {
      var hbody = document.getElementsByTagName('body')[0];
      var isJsPath = false;
      var scripts = hbody.getElementsByTagName('script');
      for (var i = 0; i < scripts.length; i++) {
        if (scripts[i].src == jsPath) {
          isJsPath = true;
          break;
        }
      }
      if (isJsPath) {
        resolve();
        return;
      }
      var domScript = document.createElement('script');
      domScript.type = 'text/javascript';
      domScript.onload = domScript.onreadystatechange = function () {
        if (!domScript.readyState || /loaded|complete/.test(domScript.readyState)) {
          resolve();
        }
      }
      domScript.onerror = function (e) {
        let errorData = {
          errorType:'syncLoadJs',
          jsPath:jsPath
        }
        that.reprotError(errorData);
        reject(e);
      }
      domScript.src = jsPath;
      hbody.appendChild(domScript);
    })
  },

  dateFormatNew (date, fmt = 'YYYY-MM-DD HH:mm:ss') {
    if (!date) {
      return ''
    }
    if (typeof date === 'string') {
      date = new Date(date.replace(/-/g, '/'))
    }
    if (typeof date === 'number') {
      date = new Date(date)
    }
    var o = {
      'M+': date.getMonth() + 1,
      'D+': date.getDate(),
      'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
      'H+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds(),
      'q+': Math.floor((date.getMonth() + 3) / 3),
      'S': date.getMilliseconds()
    }
    var week = {
      '0': '\u65e5',
      '1': '\u4e00',
      '2': '\u4e8c',
      '3': '\u4e09',
      '4': '\u56db',
      '5': '\u4e94',
      '6': '\u516d'
    }
    if (/(Y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    if (/(E+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '\u661f\u671f' : '\u5468') : '') + week[date.getDay() + ''])
    }
    for (var k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      }
    }
    return fmt
  },

  dateFormat(timestamp, formatStr = '-', isMonthlower = 0) {
    let dateTime = new Date(timestamp);
    let dateYear = dateTime.getFullYear();
    // isMonthlower=1只获取到上个月, 否者是本月
    let dateMouth = isMonthlower == 1 ? dateTime.getMonth() : dateTime.getMonth() + 1;
    let dateDay = dateTime.getDate();
    dateMouth = dateMouth < 10 ? `0${dateMouth}` : dateMouth;
    dateDay = dateDay < 10 ? `0${dateDay}` : dateDay;
    return `${dateYear}${formatStr}${dateMouth}${formatStr}${dateDay}`;
  },
  /**
    * 时间转换工具
    * 去掉秒，不显示当前年份
    * @param {*} timeStr 要转换的时间
    */
  changeTimeUtil(timeStr) {
    let nowDate = new Date();
    let timeChangeStr = timeStr.replace(/\-/g, "/");
    let strDate = new Date(timeChangeStr);
    let nowYear = nowDate.getFullYear();
    let strYear = strDate.getFullYear();
    let strMouth = strDate.getMonth() + 1;
    let strDay = strDate.getDate();
    let strHours = strDate.getHours() > 9 ? '' + strDate.getHours() : '0' + strDate.getHours();
    let strMinutes = strDate.getMinutes() > 9 ? '' + strDate.getMinutes() : '0' + strDate.getMinutes();
    let resMounth = strMouth > 9 ? '' + strMouth : '0' + strMouth;
    let resDay = strDay > 9 ? '' + strDay : '0' + strDay;
    if (nowYear == strYear) {
      return resMounth + '-' + resDay + ' ' + strHours + ':' + strMinutes;
    } else {
      return strYear + '-' + resMounth + '-' + resDay + ' ' + strHours + ':' + strMinutes;
    }
  },

  /**
  * 获取当前时间
  */
  getNowTime() {
    let date = new Date();
    let month = date.getMonth() + 1; //月份是0~11，要加1为当前月
    let strDate = date.getDate();
    let strHours = date.getHours();
    let strMin = date.getMinutes();
    let strSec = date.getSeconds();
    month = month > 9 ? month : "0" + month;
    strDate = strDate > 9 ? strDate : "0" + strDate;
    strHours = strHours > 9 ? strHours : "0" + strHours;
    strMin = strMin > 9 ? strMin : "0" + strMin;
    strSec = strSec > 9 ? strSec : "0" + strSec;
    return date.getFullYear() + '-' + month + '-' + strDate + " " + strHours + ":" + strMin + ":" + strSec;
  },

  getNowTimeFormat(format = 'YYYY-MM-DD'){
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1; //月份是0~11，要加1为当前月
    let strDate = date.getDate();
    let strHours = date.getHours();
    let strMin = date.getMinutes();
    let strSec = date.getSeconds();
    month = month > 9 ? month : "0" + month;
    strDate = strDate > 9 ? strDate : "0" + strDate;
    strHours = strHours > 9 ? strHours : "0" + strHours;
    strMin = strMin > 9 ? strMin : "0" + strMin;
    strSec = strSec > 9 ? strSec : "0" + strSec;
    let res = `${year}-${month}-${strDate}`;
    return res;
  },

  /**
   * 问答模式时间转换工具
   * @param {*} timeStr 要转换的时间
   */
  changeQaTime(timeStr) {
    let nowDate = new Date();
    let timeChangeStr = timeStr.replace(/\-/g, "/");
    let strDate = new Date(timeChangeStr);
    let nowYear = nowDate.getFullYear();
    let nowMouth = nowDate.getMonth() + 1;
    let nowDay = nowDate.getDate();
    let strYear = strDate.getFullYear();
    let strMouth = strDate.getMonth() + 1;
    let strDay = strDate.getDate();
    let strHours = strDate.getHours() > 9 ? '' + strDate.getHours() : '0' + strDate.getHours();
    let strMinutes = strDate.getMinutes() > 9 ? '' + strDate.getMinutes() : '0' + strDate.getMinutes();
    //如果是一小时以内，则返回刚刚
    //如果超过一小时，日期为今天，则返回时间
    //超过当天，返回日期
    if (nowDate - strDate < 1000 * 60 * 60) {
      return '刚刚';
    } else if (nowDate - strDate > 1000 * 60 * 60 && nowYear == strYear && nowMouth == strMouth && nowDay == strDay) {
      return strHours + ':' + strMinutes;
    } else if (nowYear == strYear) {
      let resMounth = strMouth > 9 ? '' + strMouth : '0' + strMouth;
      let resDay = strDay > 9 ? '' + strDay : '0' + strDay;
      return resMounth + '-' + resDay;
    } else {
      let resMounth = strMouth > 9 ? '' + strMouth : '0' + strMouth;
      let resDay = strDay > 9 ? '' + strDay : '0' + strDay;
      return strYear + '-' + resMounth + '-' + resDay;
    }
  },
  /**
   * 评论时间转换工具
   * @param {*} timeStr 要转换的时间
   */
  changeCommentTime(timeStr) {
    let nowDate = new Date();
    let timeChangeStr = timeStr.replace(/\-/g, "/");
    let strDate = new Date(timeChangeStr);
    let nowYear = nowDate.getFullYear();
    let nowMouth = nowDate.getMonth() + 1;
    let nowDay = nowDate.getDate();
    let strYear = strDate.getFullYear();
    let strMouth = strDate.getMonth() + 1;
    let strDay = strDate.getDate();
    let strHours = strDate.getHours() > 9 ? '' + strDate.getHours() : '0' + strDate.getHours();
    let strMinutes = strDate.getMinutes() > 9 ? '' + strDate.getMinutes() : '0' + strDate.getMinutes();
    let strSeconds = strDate.getSeconds() > 9 ? '' + strDate.getSeconds() : '0' + strDate.getSeconds();
    //如果是一小时以内，则返回刚刚
    //如果超过一小时，日期为今天，则返回时间
    //超过当天，返回日期
    if (nowDate - strDate < 1000 * 60) {
      return '刚刚';
    } else if (nowDate - strDate < 1000 * 60 * 60) {
      return (Math.floor((nowDate - strDate) / (1000 * 60))) + '分钟前';
    } else if (nowDate - strDate < 1000 * 60 * 60 * 24) {
      return (Math.floor((nowDate - strDate) / (1000 * 60 * 60))) + '小时前';
    } else if (nowYear == strYear) {
      let resMounth = strMouth > 9 ? '' + strMouth : '0' + strMouth;
      let resDay = strDay > 9 ? '' + strDay : '0' + strDay;
      return resMounth + '-' + resDay + ' ' + strHours + ':' + strMinutes + ':' + strSeconds;
    } else {
      return timeStr
    }
  },
  /**
 * 时间差转成具体时间*天*时*分*秒
 * timeTmpToStrNoDay == true:时间差转成具体时间*时*分*秒
 * @param {*} timeTmp 
 * @returns {*} timeStr
 */
  timeTmpToStr(timeTmp, isReturnObj = false, timeTmpToStrNoDay = false) {
    const ONE_DAY_TIMESTAMP = 24 * 60 * 60 * 1000;
    const ONE_HOUR_TIMESTAMP = 60 * 60 * 1000;
    const ONE_MINUTE_TIMESTAMP = 60 * 1000;
    const ONE_SECONDS_TIMESTAMP = 1000;

    //获取天数
    let dayNum = timeTmpToStrNoDay == false ? Math.floor(timeTmp / ONE_DAY_TIMESTAMP) : -1;
    let hourNum = 0;
    let minuteNum = 0;
    let secondsNum = 0;
    if (timeTmpToStrNoDay == false) {
      hourNum = Math.floor((timeTmp - dayNum * ONE_DAY_TIMESTAMP) / ONE_HOUR_TIMESTAMP);
      minuteNum = Math.floor((timeTmp - dayNum * ONE_DAY_TIMESTAMP - hourNum * ONE_HOUR_TIMESTAMP) / ONE_MINUTE_TIMESTAMP);
      secondsNum = Math.floor((timeTmp - dayNum * ONE_DAY_TIMESTAMP - hourNum * ONE_HOUR_TIMESTAMP - minuteNum * ONE_MINUTE_TIMESTAMP) / ONE_SECONDS_TIMESTAMP);
    } else {
      hourNum = Math.floor(timeTmp / ONE_HOUR_TIMESTAMP);
      minuteNum = Math.floor((timeTmp - hourNum * ONE_HOUR_TIMESTAMP) / ONE_MINUTE_TIMESTAMP);
      secondsNum = Math.floor((timeTmp - hourNum * ONE_HOUR_TIMESTAMP - minuteNum * ONE_MINUTE_TIMESTAMP) / ONE_SECONDS_TIMESTAMP);
    }

    let returnStr = '';
    let returnObj = {
      dayNum,
      hourNum,
      minuteNum,
      secondsNum,
    }
    if (dayNum > 0) {
      returnStr = `${dayNum}天${hourNum}时${minuteNum}分${secondsNum}秒`;
    } else if (hourNum > 0) {
      returnObj = {
        dayNum: -1,
        hourNum,
        minuteNum,
        secondsNum,
      }
      returnStr = `${hourNum}时${minuteNum}分${secondsNum}秒`;
    } else if (minuteNum > 0) {
      returnObj = {
        dayNum: -1,
        hourNum: -1,
        minuteNum,
        secondsNum,
      }
      returnStr = `${minuteNum}分${secondsNum}秒`;
    } else if (secondsNum > 0) {
      returnObj = {
        dayNum: -1,
        hourNum: -1,
        minuteNum: -1,
        secondsNum,
      }
      returnStr = `${secondsNum}秒`;
    }
    if (isReturnObj) {
      return returnObj;
    }
    return returnStr;
  },
  //时分秒
  timeTmpToStrTime(timeTmp) {
    const ONE_HOUR_TIMESTAMP = 60 * 60 ;
    const ONE_MINUTE_TIMESTAMP = 60 ;
    const ONE_SECONDS_TIMESTAMP = 1;

    let hourNum = Math.floor(timeTmp / ONE_HOUR_TIMESTAMP);
    let minuteNum = Math.floor((timeTmp - hourNum * ONE_HOUR_TIMESTAMP) / ONE_MINUTE_TIMESTAMP);
    let secondsNum = Math.floor((timeTmp - hourNum * ONE_HOUR_TIMESTAMP - minuteNum * ONE_MINUTE_TIMESTAMP) / ONE_SECONDS_TIMESTAMP);
    let returnStr = '';
    let returnObj = {
      hourNum,
      minuteNum,
      secondsNum,
    }
    if (hourNum > 0) {
      returnObj = {
        dayNum: -1,
        hourNum,
        minuteNum,
        secondsNum,
      }
      returnStr = `${hourNum>0?hourNum:'0'+hourNum}:${minuteNum>=10?minuteNum:'0'+minuteNum}:${secondsNum>=10?secondsNum:'0'+secondsNum}`;
    } else if (minuteNum > 0) {
      returnObj = {
        dayNum: -1,
        hourNum: -1,
        minuteNum,
        secondsNum,
      }
      returnStr = "00:"+`${minuteNum>=10?minuteNum:'0'+minuteNum}:${secondsNum>=10?secondsNum:'0'+secondsNum}`;
    } else if (secondsNum > 0) {
      returnObj = {
        dayNum: -1,
        hourNum: -1,
        minuteNum: -1,
        secondsNum,
      }
      returnStr = "00:00:"+`${secondsNum>=10?secondsNum:'0'+secondsNum}`;
    }
    return returnStr;
  },
  //分秒
  timeTmpToNsTime(timeTmp) {
    const ONE_MINUTE_TIMESTAMP = 60 ;
    const ONE_SECONDS_TIMESTAMP = 1;

    let minuteNum = Math.floor(timeTmp  / ONE_MINUTE_TIMESTAMP);
    let secondsNum = Math.floor((timeTmp - minuteNum * ONE_MINUTE_TIMESTAMP) / ONE_SECONDS_TIMESTAMP);
    let returnStr = '';
    let returnObj = {
      minuteNum,
      secondsNum,
    }
    if (minuteNum > 0) {
      returnObj = {
        minuteNum,
        secondsNum,
      }
      returnStr = `${minuteNum>=10?minuteNum:'0'+minuteNum}:${secondsNum>=10?secondsNum:'0'+secondsNum}`;
    } else if (secondsNum > 0) {
      returnObj = {
        minuteNum: -1,
        secondsNum,
      }
      returnStr = "00:"+`${secondsNum>=10?secondsNum:'0'+secondsNum}`;
    }
    return returnStr;
  },
  //dateStr = 2018-08-25 23:59:59"
  getTimeByDate: function (dateStr) {
    if (dateStr != '' && dateStr != null && dateStr != undefined) {
      let time = 0;
      let timeHead = dateStr.split(" ")[0].split("-");
      let timeEnd = dateStr.split(" ")[1].split(":");
      let date = new Date(timeHead[0], (parseInt(timeHead[1]) - 1), timeHead[2], timeEnd[0], timeEnd[1], timeEnd[2]);
      time = date.getTime();
      return time;
    } else {
      return 0;
    }
  },
  /**
   * 月份数转换成 半年  年
   * count为多少个月 例如6个月显示半年 12个月显示一年
   */
  getYearByMonthCount: function (count) {
    if (count <= 0) {
      return 0;
    }
    let str = '';
    if (Number(count) % 12 == 0) {
      str = this.formatYear(Number(count) / 12)
    } else if (Number(count) % 12 % 6 == 0) {
      str = this.formatYear(Number(count) / 12)
    } else {
      str = count + '个月'
    }
    return str
  },
  /**
   * 0.5 半年 1 一年
   */
  formatYear: function (num) {
    if (/\./g.test(num)) {
      if (num < 1) {
        return '半年';
      } else {
        return Math.floor(num) + '年半';
      }
    } else {
      return num + '年';
    }
  },
  /* 获取对应月份的天数 */
  getMonthDays(year, month) {
    let days = [31, 28, 31, 30, 31, 30, 31, 30, 30, 31, 30, 31];
    if ((year % 4 === 0) && (year % 100 !== 0 || year % 400 === 0)) {
      days[1] = 29
    }
    return days[month - 1]
  },
  hexToRgb: (hex) => {
    if (!hex) return ''
    let rgb = [];
    hex = hex.substr(1);//去除前缀 # 号
    if (hex.length === 3) { // 处理 "#abc" 成 "#aabbcc"
      hex = hex.replace(/(.)/g, '$1$1');
    }
    hex.replace(/../g, function (color) {
      rgb.push(parseInt(color, 0x10));//按16进制将字符串转换为数字
    });
    return rgb.join(",");
  },
  curEnvConfig: () => {
    let hostName = window.location.host.indexOf(".wx.ckjr001.com") != -1 ? "wx.ckjr001.com" : window.location.host;
    let env = hostName.indexOf('test') > -1 ? 'dev' : hostName.indexOf('formal') > -1 ? 'sit' : 'prod';
    return env;
  },
  toMyFixed2: (str) => {
    return (str * 1 + 0.00000001).toFixed(2) * 1;
  },
  //将超过1w的专为x.xw 如12345=1.2w
  formatTenThousand: (value) => {
    let strNum = '';
    if (value != '' && Number(value) >= 0) {
      let n = Number(value);
      if (n >= 10000) {
        strNum = ((n / 10000).toFixed(4) * 1).toFixed(1) + 'w';
      } else {
        strNum = n;
      }
    } else {
      strNum = 0;
    }
    return strNum;
  },
  isOpenIosGzhPay: (moduleType) => {
    let isIosWx = navigator.userAgent.toLowerCase().indexOf('mac') > -1 && navigator.userAgent.toLowerCase().indexOf('micromessenger') > -1;
    let gzhPayConfs = localStorage.getItem('iosGzhPayConfs') && JSON.parse(localStorage.getItem('iosGzhPayConfs'));
    //不在ios微信内 || 没有返回内容，默认可支付
    if (!isIosWx || !gzhPayConfs) {
      return true;
    }
    //后台设置为开启支付
    if (gzhPayConfs.iosGzhPayAll == 1) {
      return true;
    }
    moduleType = moduleType ? '' + moduleType : '';
    const moduleTypeMap = global.moduleTypeMap;
    if (gzhPayConfs.iosGzhPayAll == -1 || gzhPayConfs[moduleTypeMap[moduleType]] == -1) {
      return false;
    }
    return true;
  },
  isAndroidApp: () => {
    return navigator.userAgent.indexOf("APPLogin") > -1;
  },
  isAndoridNewApp: () => {
    return navigator.userAgent.indexOf("APPAndroidLogin") > -1;
  },
  isAdnroidBrower: () => {
    let u = navigator.userAgent;
    let isAnd = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;//andrio终端
    return isAnd;
  },
  iosRecoverBuy: () => {
    window.webkit.messageHandlers.iosWechatRecoverBuy.postMessage('recoverBuy');
  },
  isIOSAnonUser: () => {
    let isAnonUser = false;
    const AnonUserArr = ['18250123456'];
    let userPhone = window.localStorage.getItem('uMobile') || '';
    if (userPhone && AnonUserArr.indexOf(userPhone) > -1) {
      isAnonUser = true;
    }
    return isAnonUser;
  },
  isIosAudioApp: () => {
    return navigator.userAgent.indexOf("cj_app_ios_v1") > -1;
  },
  isAndroidAudioApp: () => {
    return navigator.userAgent.indexOf("cj_app_android_v1") > -1;
  },
  isIosVideoApp: () => {
    return navigator.userAgent.indexOf("cj_app_ios_v2") > -1;
  },
  isAndroidVideoApp: () => {
    return navigator.userAgent.indexOf("cj_app_android_v2") > -1;
  },
  getAppVersion: () => {
    let uaArr = navigator.userAgent.split(',');
    let verString = '';
    if(uaArr && uaArr.length > 0) {
      for (let i = 0; i < uaArr.length; i++) {
        if(uaArr[i].indexOf("CKJR_V_") > -1) {
          verString = uaArr[i];
          break;
        }
      }
    }
    if (verString) {
      return Number(verString.replace('CKJR_V_', ''));
    }
    return 0;
  },
  unique: (arr) => {
    if ((arr && arr.length == 0) || arr == undefined || arr == null) return
    let uniqueArr = [];
    arr.forEach(item => {
      if (!uniqueArr.some(sItem => {return JSON.stringify(sItem) == JSON.stringify(item)})) {
        uniqueArr.push(item)
      }
    })
    return uniqueArr
  },
  isIOSApp: () => {
    // return navigator.userAgent.indexOf("IOSLogin") > -1 || navigator.userAgent.indexOf('IOSNewLogin') > -1;
    return navigator.userAgent.indexOf("IOSNewApp") > -1;
  },
  isIOSAppALL: () => {
    return navigator.userAgent.indexOf("IOSLogin") > -1 || navigator.userAgent.indexOf('IOSNewLogin') > -1 || navigator.userAgent.indexOf("IOSNewApp") > -1;
  },
  isIosWechat: () => {
    return navigator.userAgent.toLowerCase().indexOf('mac') > -1 && navigator.userAgent.toLowerCase().indexOf('micromessenger') > -1
  },
  //表单验证整数
  isFormIntegerNumber: (num) => {
    var integer = /^\d+$/;
    return integer.test(num);
  },
  isPhoneNumber: (phoneStr) => {
    // var mobile = /^((13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])+\d{8})$/;
    var mobile = /^(\d{11})$/;
    return mobile.test(phoneStr);
  },
  isEmail: (str) => {
    var email = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
    return email.test(str);
  },
  isIDNo: (str) => {
    var idNo = /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    return idNo.test(str);
  },
  disSubButton: function (id) {
    var btn = document.getElementById(id);
    btn.setAttribute("disabled", "disabled");
    btn.style.backgroundColor = '#d0d0d0';
  },
  ableSubButton: function (id) {
    var btn = document.getElementById(id);
    btn.removeAttribute("disabled");
    btn.style.backgroundColor = '#fe3b5c';
  },
  isMobileUserAgent: () => {
    return (/iphone|ipad|ipod|android|android.*mobile|windows.*phone|blackberry.*mobile/i.test(window.navigator.userAgent.toLowerCase()));
  },
  IsURL: (strUrl) => {
    var regular = /^\b(((https?|ftp):\/\/)?[-a-z0-9]+(\.[-a-z0-9]+)*\.(?:com|edu|gov|int|mil|net|org|biz|info|name|museum|asia|coop|aero|[a-z][a-z]|((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d))\b(\/[-a-z0-9_:\@&?=+,.!\/~%\$]*)?)$/i
    if (regular.test(strUrl)) {
      return true;
    } else {
      return false;
    }
  },
  validateName:(name) => {
		return name.match("^([\\u4e00-\\u9fa5]{1,20}|[a-zA-Z\\.\\s]{1,20})$");
  },
  //数字和字母组成
  NumberAndLetters:(NumberAndLetters) => {
		return NumberAndLetters.match("^[0-9a-zA-Z]{1,}$");
  },
  // 判断超过200个字符
  getChineseStrLength: (str) => {
    let chStr = str;
    let reg = /([\u4E00-\u9FA5]|[\uFE30-\uFFA0])/g;
    return chStr.replace(reg, "aa").length;
  },
  //回到顶部
  toPageScrollTop: () => {
    var a = document;
    a.body.scrollTop = 0;
    a.documentElement.scrollTop = 0;
  },
  isPassword: (str) => {
    var result = str.match(/\d{6}/);
    if (result == null) return false;
    return true;
  },
  isBankCardNo: (str) => {
    var result = str.match(/\d{16}|\d{17}|\d{18}|\d{19}|\d{20}|\d{21}/);
    if (result == null) return false;
    return true;
  },
  androidAppExit() {
    if (navigator.userAgent.indexOf('APPLogin') > -1) {
      var data1 = {
        "call": "exit",
      };
      window.prompt(JSON.stringify(data1));
    }
  },
  nameLength(str, length) {
    if (str != undefined && str != '' && str != null) {
      return str.length > length ? `${str.substr(0, length)}***` : str;
    } else {
      return "未知用户";
    }
  },
  //将url查询参数通过正则表达式解析成数据字典
  getQueryObject(url) {
    url = (url && url != -1) ? url : '';
    var search = url.substring(url.lastIndexOf("?") + 1);
    var obj = {};
    var reg = /([^?&=]+)=([^?&=]*)/g;
    // [^?&=]+表示：除了？、&、=之外的一到多个字符
    // [^?&=]*表示：除了？、&、=之外的0到多个字符（任意多个）
    search.replace(reg, function (rs, $1, $2) {
      var name = decodeURIComponent($1);
      var val = decodeURIComponent($2);
      val = String(val);
      obj[name] = val;
      return rs;
    });
    return obj;
  },
  //脱离微信图片上传
  imgUpload: function (imgFiles, imgData, fromText, callBack, errorCallBack) {
    if (imgFiles == null || imgFiles.length == 0) {
      return;
    }
    let uploadFile = imgFiles[0];
    if (uploadFile.size <= 5242880) {//5M
      Vue.prototype.$loading.show({
        text: 'Loading'
      });
      console.log('---uploadFile--',uploadFile)
      let companyId = localStorage.getItem('companyId');
      let fileName = `mp_${companyId}_${uploadFile.name}`;
      let fileKey = imgData.key + (new Date().getTime()) + "_mp_" + fromText + "_" + uploadFile.name;
      let formData = new FormData();
      formData.append("key", fileKey);
      formData.append("policy", imgData.policy);
      formData.append("OSSAccessKeyId", imgData.OSSAccessKeyId);
      formData.append("success_action_status", imgData.success_action_status);
      formData.append("callback", imgData.callback);
      formData.append("signature", imgData.signature);
      formData.append("name", fileName);
      formData.append("file", uploadFile);
      this.postFileMethod(imgData.aliYunHost, formData, res => {
        if (res.data.Status == "Ok") {
          callBack && callBack(res.data.url);
          Vue.prototype.$loading.hide();
        } else {
          Vue.prototype.$showCjToast({
            text: "上传图片失败",
            type: 'warn',
          });
          errorCallBack && errorCallBack();
          Vue.prototype.$loading.hide();
        }
      }, failRes => {
        Vue.prototype.$loading.hide();
      });
    } else {
      Vue.prototype.$showCjToast({
        text: "您上传的图片太大了，不能超过5M哦",
        type: 'warn',
      });
      errorCallBack && errorCallBack();
    }
  },
  //获取阿里云的签名
  getAliSign: function (url, scallBack) {
    this.getMethod(url, function (res) {
      let aliYunSign = {
        'key': res.dir,
        'policy': res.policy,
        'OSSAccessKeyId': res.accessid,
        'success_action_status': '200',
        'callback': res.callback,
        'signature': res.signature,
        'aliYunHost': res.host
      }
      scallBack && scallBack(aliYunSign);
    })
  },
  //上传图片到阿里云的post方法
  postFileMethod: function (url, data, scallBack, errorCallBack) {
    let _method = data._method == 'put' ? data._method : 'post' //切换请求方式
    if (_method == 'put') {
      delete data._method;
    }
    ckjrRequest({
      method: _method,
      url: url,
      data: data,
      headers:{
        'Content-Type': 'multipart/form-data'
      },
    }).then(res => {
      if (res.status == 200) {
        scallBack && scallBack(res.data);
      } else {
        Vue.prototype.$showCjToast({
          text: "上传失败",
          type: 'warn',
        });
        errorCallBack && errorCallBack();
      }
    });
  },

  //安卓、ios分享
  appShare: function (event) {
    let u = navigator.userAgent;
    let isAndroid = u.indexOf('APPLogin') > -1 || u.indexOf('APPH5Login') > -1; //android终端, APPH5Login:走h5支付，又要分享的时候（目前只有优匹定制采用）。
    let isiOS = u.indexOf('IOSLogin') > -1; //ios终端
    let isNewiOS = u.indexOf('IOSNewLogin') > -1 || navigator.userAgent.indexOf("IOSNewApp") > -1; //ios终端
    if (isAndroid == true || isiOS == true || isNewiOS == true) {
      window["appShare"] = event.appShare;
    }
  },
  appShareTrue: function (title, shareImg, shareUrl, shareDesc) {
    title = title || window.localStorage.getItem("shareTitle");
    shareImg = shareImg || window.localStorage.getItem("shareLogo");
    shareUrl = shareUrl || window.location.href.split("#")[0] + "#/" + "?refereeId=" + localStorage.getItem("userId");
    shareDesc = shareDesc || window.localStorage.getItem("shareDesc");
    var time = (new Date()).getTime();
    var data = {
      title: title,
      shareImg: shareImg,
      shareUrl: shareUrl,
      shareDesc: shareDesc
    };
    data[time] = time;
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('APPLogin') > -1 || u.indexOf('APPH5Login') > -1; //android终端, APPH5Login:走h5支付，又要分享的时候（目前只有优匹定制采用）
    var isiOS = u.indexOf('IOSLogin') > -1; //ios终端
    var isNewiOS = u.indexOf('IOSNewLogin') > -1 || navigator.userAgent.indexOf("IOSNewApp") > -1; //ios终端
    if (isAndroid == true) {
      var data1 = {
        "call": "share",
        "data": data
      };
      window.prompt(JSON.stringify(data1));
    } else if (isiOS == true || isNewiOS == true) {
      if (isiOS == true) {
        iosWechatShare(JSON.stringify(data));
      } else {
        window.webkit.messageHandlers.iosWechatShare.postMessage(JSON.stringify(data));
      }
    }
  },
  //新版发送数据给app的webview
  sendDataToAppWebview(methodName, sendData = {}) {
    if (utilJs.isAndroidApp()) {
      var data1 = {
        "call": methodName,
        "data": sendData
      };
      //没数据不传参，不然安卓那边会掉不到接口
      if(JSON.stringify(sendData) == '{}'){
        window.androidWechatRoute[methodName]();
      }else{
        window.androidWechatRoute[methodName](JSON.stringify(data1));
      }
    } else if (utilJs.isIOSAppALL()) {
      window.webkit.messageHandlers[methodName].postMessage(JSON.stringify(sendData));
    }
  },
  sendDataToApp(methodName, sendData = {}) {
    if (utilJs.isAndroidApp()) {
      var data1 = {
        "call": methodName,
        "data": sendData
      };
      // window.prompt(JSON.stringify(data1));
      window.androidWechatRoute.doAction(JSON.stringify(data1));
    } else if (utilJs.isIOSAppALL()) {
      window.webkit.messageHandlers[methodName].postMessage(JSON.stringify(sendData));
    }
  },
  // 判断是否链动商品及获取链动信息
  getChainInfo(prodType, prodId) {
    return new Promise(function (resolve, reject) {
      let enableChainModel = localStorage.getItem("enableChainModel");
      if (enableChainModel == 1) {
        utilJs.getMethod(`${global.apiurl}chainProds/getProdChainInfo?prodId=${prodId}&prodType=${prodType}`, res => {
          resolve(res);
        }, failRes => {
          reject(failRes)
        })
      } else {
        resolve(false);
      }
    })
  },
  /**
   * 
   * @param {*} type  record 录音 video 视频 
   * @param {*} methodName 方法名称
   * @param {*} sendData 发送的数据
   */
  sendDataToAppNew(type, methodName, sendData = {}) {
    var data1 = {
      "call": methodName,
      "data": sendData
    };
    if (utilJs.isAndroidApp()) {
      // window.prompt(JSON.stringify(data1));
      window.androidWechatRoute.callHandler(type,JSON.stringify(data1));
    } else if (utilJs.isIOSAppALL()) {
      // window.webkit.messageHandlers[methodName].postMessage(JSON.stringify(sendData));
      window.webkit.messageHandlers[type].postMessage(JSON.stringify(data1));
    }
  },
  //安卓、ios支付接口
  appPay: function (data, isFromOrder, isFromInvite, ckFrom, type, backUrl) {
    let u = navigator.userAgent;
    let isAndroid = u.indexOf('APPLogin') > -1; //android终端
    let isiOS = u.indexOf('IOSLogin') > -1; //ios终端
    let isNewiOS = u.indexOf('IOSNewLogin') > -1 || navigator.userAgent.indexOf("IOSNewApp") > -1; //ios终端
    if (isAndroid == true) {
      let wechatPay = {
        "call": "pay",
        "data": {
          "orderId": data.orderId,
          "isFromOrder": isFromOrder,
          "isFromInvite": isFromInvite,
          "ckFrom": ckFrom,
          "type": type,
          "backUrl": backUrl,
          "token": localStorage.getItem("token")
        }
      };
      window.prompt(JSON.stringify(wechatPay));
    } else if (isiOS == true || isNewiOS == true) {
      let data1 = {
        "orderId": data.orderId,
        "isFromOrder": isFromOrder,
        "isFromInvite": isFromInvite,
        "ckFrom": ckFrom,
        "type": type,
        "backUrl": backUrl,
        "token": localStorage.getItem("token")
      };
      // let sdata = JSON.stringify(data1);
      if (isiOS == true) {
        iosWechatPay(data1);
      } else {
        window.webkit.messageHandlers.iosWechatPay.postMessage(data1);
      }
    }
  },
  isWeiXin: () => {
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
      return true;
    } else {
      return false;
    }
  },
  wechatConfig: function (shareUrl, title, shareImg, shareDesc, callback, moreApiList, otherOption) {
    if (!this.isWeiXin()) {
      return;
    }
    title = title != '' ? title : window.localStorage.getItem("shareTitle");
    shareImg = shareImg != '' ? shareImg : window.localStorage.getItem("shareLogo");
    shareImg = encodeURI(shareImg);
    shareUrl = shareUrl != '' ? shareUrl : (window.location.href.split("#")[0] +
      "#/" + "?refereeId=" + localStorage.getItem("userId"));
    shareUrl = shareUrl.indexOf("/#/") != -1 ? shareUrl.replace("#", "?#") : shareUrl;
    shareDesc = typeof shareDesc !== 'undefined' && shareDesc !='' ? shareDesc : (window.localStorage.getItem("shareDesc") || '点击查看详情');
    if (this.isAdnroidBrower() && shareUrl.split("/")[5] == "?#") { //暂时处理分享问题
      shareUrl = shareUrl.split("#")[0] + (new Date().getTime()) + "#" + shareUrl.split("#")[1];
    }
    if (sessionStorage.getItem('promotedAccountId')) {
      if (shareUrl.split("#")[1].indexOf("?") > -1) {
        shareUrl = shareUrl + '&promotedAccountId=' + sessionStorage.getItem('promotedAccountId');
      } else {
        shareUrl = shareUrl + '?promotedAccountId=' + sessionStorage.getItem('promotedAccountId');
      }
    }
    /* 'updateAppMessageShareData', 'updateTimelineShareData', */
    let jsApiList = ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareWeibo', 'onMenuShareQZone', 'hideMenuItems','showAllNonBaseMenuItem', 'hideAllNonBaseMenuItem', 'getNetworkType', "openLocation", "getLocation", "openAddress"];
    if (moreApiList) {
      jsApiList = [
        "onMenuShareTimeline",
        "onMenuShareAppMessage",
        "onMenuShareQQ",
        "onMenuShareWeibo",
        "onMenuShareQZone",
        "showAllNonBaseMenuItem",
        "hideAllNonBaseMenuItem",
        "startRecord",
        "stopRecord",
        "onVoiceRecordEnd",
        "playVoice",
        "pauseVoice",
        "stopVoice",
        "onVoicePlayEnd",
        "uploadVoice",
        "downloadVoice",
        "chooseImage",
        "previewImage",
        "uploadImage",
        "downloadImage",
        "chooseWXPay",
        "hideMenuItems",
        "openLocation",
        "getLocation",
        "openAddress",
        "openBusinessView"
      ];
    }

    let companyId = window.location.href.split("/")[4];
    if (["9pjbvj", "79jayb"].includes(companyId)) { // 此商家因为分享必须要用新的接口，不然移动端分享就是失败的
      jsApiList.push('updateAppMessageShareData'); // 特殊处理
      jsApiList.push('updateTimelineShareData');
    }

    let url = checkApiHp(global.apiurl + 'mp/jsConfig');
    let surl = navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) ? (localStorage.getItem('firstPage') ? localStorage.getItem('firstPage') : window.location.href.split("#")[0] + '#/') : window.location.href;
    let reg = /^(\&*\w+=*\w*\&*)*#$/;
    if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) && reg.test(surl.split("/")[5])) {
      surl = surl.split(surl.split("/")[5])[0] + "?#" + surl.split(surl.split("/")[5])[1];
    }
    let $this = this;
    let datas = {
      url: surl,
      jsApiList: jsApiList
    };
    if (otherOption && otherOption.firstConfig && otherOption.firstConfig == 1) {
      datas.c = localStorage.getItem("companyId");
    }
    datas.openTagList = ['wx-open-audio'];
    /* if (otherOption && otherOption.isWxOpenAudio == 1) {
      datas.openTagList.push('wx-open-audio');
    } */
    if (otherOption && otherOption.isWxOpenLaunchWeap == 1) {
      datas.openTagList.push('wx-open-launch-weapp');
    }
    
    ckjrRequest({
      method: 'post',
      url: url,
      data: datas,
    }).then(res => {
      if (res.data.statusCode == 200) {
        let data = res.data.data;
        $this.initWeiXin(shareUrl, title, shareImg, data, shareDesc, callback, otherOption);
      } else if (res.data.statusCode == 500) {
        sessionStorage.setItem("jsConfigError", "1");
      }
    }).catch(function (error) {
      console.log(error);
    });
    utilJs.getEnv().then(res => { // 小程序分享时，多传分享参数
      if (res === 'wxApp') {
        utilJs.miniProPostMsg({
          title: title,
          shareImg: shareImg,
          shareDesc: shareDesc,
          shareUrl: shareUrl,
          otherOption: otherOption
        });
      }
    })
    //}
  },
  initWeiXin: function (shareUrl, title, shareImg, data, shareDesc, callback, otherOption) {
    if (this.isWeiXin()) {
      wx.config(data);
      if (shareDesc == "null" || shareDesc == null || shareDesc == '' || shareDesc.length == 0 || shareDesc == undefined) {
        shareDesc = '点击查看详情';
      }
      if (shareImg == "null" || shareImg == null || shareImg == '' || shareImg.length == 0 || shareImg == undefined) {
        shareImg = window.location.protocol + '//' + window.location.hostname + '/static/i/wechatshare.png';
      }
      let isNeedCompression = typeof value === "string" && value.indexOf(".aliyuncs.com") > -1 && value.indexOf(".aliyuncs.com/assets/") == -1 && value.indexOf(".gif") == -1 && value.indexOf(".GIF") == -1 && value.indexOf("?x-oss-process=") == -1;
      shareImg = shareImg.replace('ck-bkt-knowledge-payment.oss-cn-hangzhou.aliyuncs.com', 'kposshzcdn.ckjr001.com'); // use cdn
      shareImg = shareImg.replace('knowledge-payment.oss-cn-beijing.aliyuncs.com', 'cdn-oss-beijing.myckjr.com'); // use cdn
      if (isNeedCompression) {
        shareImg = shareImg + "?x-oss-process=style/w800";
      }
      if (shareUrl.split("#/")[1].indexOf("?") > -1) { //先加上试试看吧，微信访问不了报xss攻击
        shareUrl += '&curTimestamp=' + (new Date().getTime());
      } else {
        shareUrl += '?curTimestamp=' + (new Date().getTime());
      }
      let mdData = {
        u: localStorage.getItem("userId"),
        c: localStorage.getItem("companyId"),
        shareUrl: shareUrl
      }
      wx.ready(() => {
        if ((!sessionStorage.getItem("jsConfigError") || sessionStorage.getItem("jsConfigError") != 1) && window.location.href.indexOf("#/homePage/course/voice") > -1) {
          document.addEventListener('WeixinOpenTagsError', function (e) {
            console.error(e.detail.errMsg); // 无法使用开放标签的错误原因，需回退兼容。仅无法使用开放标签，JS-SDK其他功能不受影响
            sessionStorage.setItem("jsConfigError", "1");
            if (window.location.href.split("#")[1].indexOf("?") > -1) {
              window.location.href = `${window.location.href}&time=${new Date().getTime()}`;
            } else {
              window.location.href = `${window.location.href}?time=${new Date().getTime()}`;
            }
            window.location.reload();
          });
        }
        wx.updateAppMessageShareData({ // 需在用户可能点击分享按钮前就先调用
          title: title, // 分享标题
          desc: shareDesc, // 分享描述
          link: shareUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: shareImg, // 分享图标
          success: function () {
            // 设置成功
            utilJs.wechatMD('share', mdData); //分享埋点
            // callback(shareUrl); 先去掉，因为这个分享是没办法分享后执行任何操作的，微信那边避免诱导分享
            reportPageShareSuccess(shareUrl);
          }
        });
        wx.updateTimelineShareData({ // 需在用户可能点击分享按钮前就先调用
          title: title, // 分享标题
          link: shareUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: shareImg, // 分享图标
          success: function () {
            // 设置成功
            utilJs.wechatMD('share', mdData); //分享埋点
            reportPageShareSuccess(shareUrl);
            // callback(shareUrl);
          }
        });
        wx.onMenuShareAppMessage({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          title: title, // 分享标题
          desc: shareDesc,
          link: shareUrl,
          imgUrl: shareImg,
          success: function () {
            // 用户确认分享后执行的回调函数
            utilJs.wechatMD('share', mdData); //分享埋点
            reportPageShareSuccess(shareUrl);
            callback && callback(shareUrl);
          },
          cancel: function () {
            // 用户取消分享后执行的回调函数
            utilJs.wechatMD('share', mdData);
            reportPageShareSuccess(shareUrl);
            console.log("微信分失败享链接1", shareUrl);
          }
        });

        wx.onMenuShareTimeline({
          title: title, // 分享标题
          desc: shareDesc,
          link: shareUrl,
          imgUrl: shareImg,
          success: function () {
            // 用户确认分享后执行的回调函数
            console.log("微信分享链接2", shareUrl);
            utilJs.wechatMD('share', mdData);
            reportPageShareSuccess(shareUrl);
            callback && callback(shareUrl);
          },
          cancel: function () {
            // 用户取消分享后执行的回调函数
            utilJs.wechatMD('share', mdData);
            console.log("微信分失败享链接2", shareUrl);
          }
        });

        /*wx.onMenuShareQQ({
          title: title, // 分享标题
          desc: shareDesc,
          link: shareUrl,
          imgUrl: shareImg,
          success: function () {
            // 用户确认分享后执行的回调函数
            callback();
          },
          cancel: function () {
            // 用户取消分享后执行的回调函数
          }
        });*/

        wx.onMenuShareWeibo({
          title: title, // 分享标题
          desc: shareDesc,
          link: shareUrl,
          imgUrl: shareImg,
          success: function () {
            // 用户确认分享后执行的回调函数
            utilJs.wechatMD('share', mdData);
            reportPageShareSuccess(shareUrl);
            callback && callback();
          },
          cancel: function () {
            utilJs.wechatMD('share', mdData);
            // 用户取消分享后执行的回调函数
          }
        });

        wx.onMenuShareQZone({
          title: title, // 分享标题
          desc: shareDesc,
          link: shareUrl,
          imgUrl: shareImg,
          success: function () {
            // 用户确认分享后执行的回调函数
            utilJs.wechatMD('share', mdData);
            reportPageShareSuccess(shareUrl);
            callback && callback();
          },
          cancel: function () {
            // 用户取消分享后执行的回调函数
            utilJs.wechatMD('share', mdData);
          }
        });
        if (otherOption && otherOption.hideAllNonBaseMenuItem) {
          wx.hideAllNonBaseMenuItem();
        }else{
          wx.showAllNonBaseMenuItem();
        }
      });
      wx.error(function (res) {
        console.log("微信分享失败", res);
        let errorData = {
          uA: navigator.userAgent,
          res: JSON.stringify(res),
          userId: localStorage.getItem("userId"),
          companyId: localStorage.getItem("companyId"),
          type: 'wx.error',
          curUrl: window.location.href,
          wxInitData: JSON.stringify(data)
        }
        utilJs.reprotError(errorData)
        if ((!sessionStorage.getItem("jsConfigError") || sessionStorage.getItem("jsConfigError") != 1) && (res.errMsg == "config:invalid signature" || res.errMsg == "config:fail") && (window.navigator.userAgent.indexOf('Android') > -1 || window.navigator.userAgent.indexOf('Adr') > -1) && window.location.href.indexOf("#/homePage/course/voice") > -1) {
          sessionStorage.setItem("jsConfigError", "1");
          if (window.location.href.split("#")[1].indexOf("?") > -1) {
            window.location.href = `${window.location.href}&time=${new Date().getTime()}`;
          } else {
            window.location.href = `${window.location.href}?time=${new Date().getTime()}`;
          }
          window.location.reload();
        }
      });
    }
  },
  // 公共埋点接口 ty==share是分享埋点
  wechatMD(ty, data) {
    let sorceData = {
      ty: ty,
      data: data
    }
    ckjrRequest({
      method: 'post',
      url: `${global.apiurl}common/report`,
      data: sorceData,
    });
  },

  //余额支付
  yuePay: function (data, scallBack, ecallBack) {
    data.reservedRefereeId = localStorage.getItem("reservedRefereeId") || ''; //支付即绑定关系
    ckjrRequest({
      method: 'post',
      url: global.apiurl + 'payment/balance',
      data: data,
    }).then(res => {
      console.log(res)
      if (res.status == 200 && res.data.statusCode == 200) {
        scallBack && scallBack();
      } else {
        let msg = res.data != null && res.data.msg != null ? res.data.msg : "系统错误"
        // 中文提示和错误码换行显示
        msg = msg.replace('（', '<br>（')
        Vue.prototype.$showCjToast({
          text: msg,
          type: 'warn',
        });
        ecallBack && ecallBack(res.data != null && res.data.msg != null ? res.data.msg : "系统错误");
      }
    }).catch(error => {
      console.log(error);
      Vue.prototype.$showCjToast({
        text: "余额支付请求失败",
        type: 'warn',
      });
    });
  },

  //微信支付
  wechatPay: function (data, scallBack, ecallBack) {
    if (localStorage.getItem('isWxApp')) {
      data.goUrl = encodeURIComponent(data.goUrl)
      data.pathFrom = encodeURIComponent(data.pathFrom)
      utilJs.miniProgramGoTo("replace", "/pages/member/wechatPay/index", data)
    } else{
    this.wechatPayMethod('payment/wxpayConf', data, scallBack, ecallBack);
    }
  },
  //商城余额支付
  yueMallPay: function (data, scallBack, ecallBack) {
    data.reservedRefereeId = localStorage.getItem("reservedRefereeId") || ''; //支付即绑定关系
    ckjrRequest({
      method: 'post',
      url: global.apiurl + 'payment/mallBalance',
      data: data,
    }).then(res => {
      console.log(res)
      if (res.status == 200 && res.data.statusCode == 200) {
        scallBack();
      } else {
        Vue.prototype.$showCjToast({
          text: res.data != null && res.data.msg != null ? res.data.msg : "系统错误",
          type: 'warn',
        });
        ecallBack && ecallBack();
      }
    }).catch(error => {
      console.log(error);
      Vue.prototype.$showCjToast({
        text: "余额支付请求失败",
        type: 'warn',
      });
    });
  },
  //商城微信支付todo
  wechatMallPay: function (data, scallBack, ecallBack) {
    if (localStorage.getItem('isWxApp')) {
      data.goUrl = encodeURIComponent(data.goUrl)
      utilJs.miniProgramGoTo("replace", "/pages/member/wechatPay/index", data)
    } else{
      this.wechatPayMethod('payment/mallWxpayConf', data, scallBack, ecallBack);
    }
  },
  wechatPayMethod: function (url, data, scallBack, ecallBack) {
    if (!utilJs.isWeiXin() && utilJs.isMobileUserAgent() && !utilJs.isIOSAppALL() && !utilJs.isAndroidApp()) {
      data.wxpayType = 'MWEB';
      data.redirectUrl = data.goUrl || window.location.href; // h5支付的回调地址
      if (!!data.goUrl) {
        delete data.goUrl
      }
    }
    data.reservedRefereeId = localStorage.getItem("reservedRefereeId") || ''; //支付即绑定关系
    data.frontUrl = `${window.location.href.split("#")[0]}#/member/myOrder/allOrderList?rbPay=1`;//日本支付后回调地址
    let $this = this;
    ckjrRequest({
      method: 'post',
      url: global.apiurl + url,
      data: data,
    }).then(res => {
      if (res.status == 200 && res.data.statusCode == 200) {
        if (res.data.data.isSubMch == 1 && data.goUrl) { //isSubMch： 1 服务商二级商户，0不是
          localStorage.setItem("goldPlanBackUrl", data.goUrl); //微信点击计划回调路径
        }
        let jsApiParameters = res.data.data.data || {};
        //日本支付定制专用，需要跳出系统支付
        if (jsApiParameters.h5payURL) {
          window.location.href = jsApiParameters.h5payURL;
          return;
        }
        // 微信h5支付
        if (res.data.data.mweb_url) {
          window.location.href = res.data.data.mweb_url;
          return;
        }
        let WeixinJSBridge = window.WeixinJSBridge || window.parent.WeixinJSBridge;
        if (typeof WeixinJSBridge == "undefined") {
          if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', $this.jsApiCall(jsApiParameters, scallBack, ecallBack), false);
          } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', $this.jsApiCall(jsApiParameters, scallBack, ecallBack));
            document.attachEvent('onWeixinJSBridgeReady', $this.jsApiCall(jsApiParameters, scallBack, ecallBack));
          }
        } else {
          $this.jsApiCall(jsApiParameters, scallBack, ecallBack);
        }
      } else {
        Vue.prototype.$showCjToast({
          text: res.data != null && res.data.msg != null ? res.data.msg : "系统错误",
          type: 'warn',
        });
        ecallBack();
      }
    }).catch(error => {
      console.log(error);
      ecallBack();
      Vue.prototype.$showCjToast({
        text: "微信支付请求失败",
        type: 'warn',
      });
    });
  },
  jsApiCall: function (jsApiParameters, scallBack, ecallBack) {
    let WeixinJSBridge = window.WeixinJSBridge || window.parent.WeixinJSBridge;
    WeixinJSBridge.invoke(
      'getBrandWCPayRequest',
      jsApiParameters,
      function (res) {
        WeixinJSBridge.log(res.err_msg);
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          Vue.prototype.$showCjToast({
            text: '微信支付成功',
            type: 'success',
          });
          scallBack();
        } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
          ecallBack();
        } else if (res.err_msg == 'get_brand_wcpay_request:fail') {
          let errorData = {
            uA: navigator.userAgent,
            res: JSON.stringify(res),
            userId: localStorage.getItem("userId"),
            companyId: localStorage.getItem("companyId"),
            curPageUrl: window.location.href,
          }
          utilJs.reprotError(errorData)
          Vue.prototype.$showCjToast({
            text: '微信支付失败',
            type: 'warn',
          });
          ecallBack();
        }
      }
    );
  },
  wxCreditPay(packageTmp, creditPayCallBack) {
    let wechatInfo = navigator.userAgent.match(/MicroMessenger\/([\d\.]+)/i);
    let wechatVersion = wechatInfo[1];
    if (compareVersion(wechatVersion, '7.0.5') >= 0) {
      goToWXScore(packageTmp, creditPayCallBack);
    } else {
      // 提示用户升级微信客户端版本
      window.href = 'https://support.weixin.qq.com/cgi-bin/readtemplate?t=page/common_page__upgrade&text=text005&btn_text=btn_text_0'
    }
    /**
     * 跳转微信支付分
     */
    function goToWXScore(packageTmp, creditPayCallBack) {
      let queryString = 'package=' + encodeURIComponent(packageTmp);
      wx.checkJsApi({
          jsApiList: ['openBusinessView'], // 需要检测的JS接口列表
          success: function (res) {
          // 以键值对的形式返回，可用的api值true，不可用为false
          // 如：{"checkResult":{"openBusinessView":true},"errMsg":"checkJsApi:ok"}
          if (res.checkResult.openBusinessView) {
              console.log('checkResult.openBusinessView')
              wx.invoke(
                  'openBusinessView', {
                    businessType: 'wxpayScorePlan',
                    queryString: queryString
                  },
                  function (res) {
                    console.log('openBusinessView_wxpayScorePlan', res)
                  // 从支付分返回时会执行这个回调函数
                      if (parseInt(res.err_code) === 0) {
                        console.log('成功')
                        creditPayCallBack && creditPayCallBack();
                      // 返回成功 
                      } else {
                        console.log('失败', res)
                        Vue.prototype.$showCjToast({
                          text: "支付分签约失败，请重新再试",
                          type: "warn",
                        });
                      // 返回失败
                      }
                  });
              }
          }
      });
    }
    /**
      * 版本号比较
      * @param {string
    } v1 
      * @param {string
    } v2 
      */
    function compareVersion(v1, v2) {
        v1 = v1.split('.')
        v2 = v2.split('.')
        const len = Math.max(v1.length, v2.length)
      
        while (v1.length < len) {
          v1.push('0')
        }
        while (v2.length < len) {
          v2.push('0')
        }
      
        for (let i = 0; i < len; i++) {
          const num1 = parseInt(v1[i])
          const num2 = parseInt(v2[i])
      
          if (num1 > num2) {
            return 1
          } else if (num1 < num2) {
            return -1
          }
        }
        return 0
    }
  },
  wxReceivePayment(transferData, creditPayCallBack) {
    console.log('transferData', transferData)
    wx.checkJsApi({
      jsApiList: ['requestMerchantTransfer'],
      success: function (res) {
        if (res.checkResult['requestMerchantTransfer']) {
          WeixinJSBridge.invoke('requestMerchantTransfer', {
              mchId: transferData.mchId,
              appId: transferData.appId,
              package: transferData.package,
            },
            function (res) {
              console.log('wxReceivePayment', res)
              if (res.err_msg === 'requestMerchantTransfer:ok') {
                creditPayCallBack && creditPayCallBack()
                // res.err_msg将在页面展示成功后返回应用时返回success，并不代表付款成功
              }
            }
          );
        } else {
          alert('你的微信版本过低，请更新至最新版本。');
        }
      }
    });
  },
  //后台编辑器详情页html的请求,注：只适合编辑器的内容，不含js代码块的，用于v-html的代码片段
  getPageHtml: (pageUrl, callBack, errorCallBack) => {
    ckjrRequest({url: pageUrl}).then(res => {
      if (res.status == 200) {
        // callBack && callBack(res.data);
        callBack && callBack(res.data.replaceAll("ck-bkt-knowledge-payment.oss-cn-hangzhou.aliyuncs.com", "kposshzcdn.ckjr001.com"));
      } else {
        errorCallBack && errorCallBack(res);
      }
    }).catch((error) => {
      console.log(error);
    });
  },

  httpRequest(url, data = {}, method = 'get', callBack, errorCallBack){
    if (url.indexOf("/submitOrder") > -1) { //下订单接口用于支付即绑定上下级关系
      if (localStorage.getItem("reservedRefereeId")) {
        data.reservedRefereeId = localStorage.getItem("reservedRefereeId") || -1; //支付即绑定关系
      }
      if (data.payMethod && !utilJs.isWeiXin() && !utilJs.isMobileUserAgent() && !utilJs.isIOSAppALL() && !utilJs.isAndroidApp() && data.payMethod == 1) {
        let hurl = data.fromRoute ? data.fromRoute : window.location.href;
        let qrUrl = qr.getQrUrl({ url: hurl, size: 120 });
        if (url.indexOf("goodsOrders") > -1) {
          Vue.prototype.$cjConfirm({
            title: '请扫码在手机端重新下单',
            message:  `<img src="${qrUrl}" style="margin-top: 10px;" class="c-ww200 c-hh200 c-center"/>`,
            showCancelButton: false,
            onConfirm: ()=>{
              window.location.reload(true);
            }
          })
          return
        }
        Vue.prototype.$cjConfirm({
          title: 'pc微信扫码支付',
          message:  `<img src="${qrUrl}" style="margin-top: 10px;" class="c-ww200 c-hh200 c-center"/><p style="margin-top: 10px;">请使用<span style="color: red">当前账号的微信扫码</span>支付</p>`,
          confirmText: '支付完成',
          cancelText: "取消支付",
          onConfirm: () => {
            window.history.go(-1);
          },
          onCancel: () => {
            window.location.reload(true);
          }
        })
        return;
      }
    }
    ckjrRequest({
      method: method,
      url: url,
      data: data,
    }).then(res => {
      //关闭详情页的骨架屏
      if (data.isSkeleton == 1 || url.includes('isSkeleton=1')) {
        store.commit('updateSkeletonStatus', {
          isSkeleton: false
        })
      }
      //取消loading
      if (store.state.oem_store.isLoading) {
        store.commit('updateLoadingStatus', {
          isLoading: false
        });
      }
      Vue.prototype.$loading.hide();
      //成功返回
      if (res.status == 200 && res.data.statusCode == 200) {
        callBack && callBack(res.data.data);
        return;
      }
      //安卓app未找到用户退出
      if (utilJs.isAndroidApp() && (res.data.msg.includes('未找到该用户') || res.data.statusCode == 10001)) {
        window.localStorage.clear();
        utilJs.androidAppExit();
        return;
      }
      //公众号未找到用户退出重新登录
      if (res.data.statusCode == 10001) {
        Vue.prototype.$cjConfirm({
          message:  `已在其他设备登录，请退出重新登录！`,
          showCancelButton: false,
          onConfirm: ()=>{
            if (utilJs.isIOSAppALL()) {
              window.webkit.messageHandlers.iosWechatLoginOut.postMessage('loginOut');
            } else { // 除了微信浏览器下多账号登录
              window.localStorage.clear();
              location.href = '?#/homePage/login/bindMobile?isLogin=1';
            }
          }
        })
        return;
      }
      //系统繁忙
      if (res.data.statusCode == 500 && res.data.msg.includes('system busy')) {
        store.commit("updateShowSystemErrorModal",  true);
        return;
      }
      //未找到用户清缓存处理
      let isMobileBrowser = !utilJs.isWeiXin() && !utilJs.isIOSAppALL() && !utilJs.isAndroidApp(); // 是否是非微信浏览器
      if (res.data.msg.includes('未找到该用户') || res.data.statusCode == 403 || res.status == 403 || (res.data.statusCode == 500 && res.data.error && res.data.errors.includes && res.data.errors.includes('未找到该用户') && isMobileBrowser)) {
        let reservedRefereeId = localStorage.getItem("reservedRefereeId") || '';
        let pcFromPath = localStorage.getItem("pcFromPath") || '';
        if ((navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1) && utilJs.isWeiXin() && localStorage.getItem("companyId")) {
          // 把之前的cookie设置过期，防止cookie不停地增加导致http request 400错误
          let exp = new Date();
          exp.setTime(exp.getTime() - 1);
          document.cookie = localStorage.getItem("companyId") + "|token=;expires=" + exp.toGMTString() + ";path=/";
        }
        localStorage.clear();
        utilJs.setStoreId();
        localStorage.setItem("reservedRefereeId", reservedRefereeId);
        localStorage.setItem("pcFromPath", pcFromPath);
        if (utilJs.isAndroidApp()) {
          utilJs.androidAppExit();
          return;
        }
        if (utilJs.isIOSAppALL()) {
          window.webkit.messageHandlers.iosWechatLoginOut.postMessage('loginOut');
        }
        if (window.location.href.split('?').length > 2) {
          window.location.href = `${window.location.href}&time=${new Date().getTime()}`;
        } else {
          window.location.href = `${window.location.href}?time=${new Date().getTime()}`;
        }
        window.location.reload(true);
        return;
      }
      //接口统一报错处理
      if (res.data.statusCode == 500) {
        //pc扫码登录接口报错不做任何处理
        if(url.indexOf("pc/login/hasQrcodeLogined") != -1 && res.data.msg && res.data.msg.includes("还未登陆")){
          return;
        }
        if (res.data.errorType && res.data.errorType == "companyClose") {
          window.location.href = 'https://' + window.location.host + '/closePlatform.html';
        } else {
          Vue.prototype.$showCjToast({
            text: res.data != null && res.data.msg != null ? res.data.msg : "系统错误",
            type: 'warn',
          });
          errorCallBack && errorCallBack(res);
        }
        return;
      }
      // 609 判断面授课是否有权限
      if (res.data.statusCode == 609) {
        errorCallBack && errorCallBack(res);
        return;
      }
      // 405 模块无权限查看 跳转到黑名单页面
      if (res.data.statusCode == 405) { 
        location.href = '?#/error/blacklistError';
        return;
      }
      Vue.prototype.$showCjToast({
        text: res.data != null && res.data.msg != null ? res.data.msg : "系统错误",
        type: 'warn',
      });
      errorCallBack && errorCallBack(res);
    }).catch((error)=> {
      if (store.state.oem_store.isSkeleton) {
        store.commit('updateSkeletonStatus', {
          isSkeleton: false
        })
      }
      if (store.state.oem_store.isLoading) {
        store.commit('updateLoadingStatus', {
          isLoading: false
        });
      }
      Vue.prototype.$loading.hide();
      if(localStorage.getItem('companyId') == 'm8rmjd' && !url.includes('common/reportError')){
        let errorData = {
          errorType:'GetMethodError',
          errorMsg:error.message,
          errorStack: error.stack && JSON.stringify(error.stack),
          errorUrl: url
        }
        utilJs.reprotError(errorData);
      }
      if (error.response && error.response.status >= 400 && error.response.status < 500) {
          if (error.response.status == 403) {
            let reservedRefereeId = localStorage.getItem("reservedRefereeId")  || '';
            if ((navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1) && utilJs.isWeiXin() && localStorage.getItem("companyId")) {
              // 把之前的cookie设置过期，防止cookie不停地增加导致http request 400错误
              let exp = new Date();
              exp.setTime(exp.getTime() - 1);
              document.cookie = localStorage.getItem("companyId") + "|token=;expires=" + exp.toGMTString() + ";path=/";
            }
            localStorage.clear();
            utilJs.setStoreId();
            if (reservedRefereeId != '') {
              localStorage.setItem("reservedRefereeId", reservedRefereeId);
            }
            if (utilJs.isAndroidApp()) {
              utilJs.androidAppExit();
              return;
            }
            if (utilJs.isIOSAppALL()) {
              window.webkit.messageHandlers.iosWechatLoginOut.postMessage('loginOut');
            }
            window.location.reload();
          } else {
            Vue.prototype.$showCjToast({
              text: "请求发送失败",
              type: 'warn',
            });
          }
      } else if (error.request) {
        if (error.request.status == 0 && !sessionStorage.getItem('isMpGetError')) {
          sessionStorage.setItem('isMpGetError', 1);
          utilJs.getMethod(url, data, callBack, errorCallBack);
        } else {
          sessionStorage.removeItem('isMpGetError');
          Vue.prototype.$showCjToast({
            text: '网络请求超时',
            type: 'warn',
          });
        }
      }
    });
  },

  getMethod: (getUrl, callBack, errorCallBack, params = {}) => {
    return utilJs.httpRequest(getUrl, params, 'get', callBack,errorCallBack);
  },

  postMethod: (url, data = {}, callBack, errorCallBack) => {
    let _method = data && data._method == 'put' ? data._method : 'post' //切换请求方式
    if (_method == 'put') {
      delete data._method;
    }
    return utilJs.httpRequest(url, data, _method, callBack, errorCallBack);
  },

  reprotError(data) {
    let sorceData = {
      fromApp: 'gzh',
      uA: navigator.userAgent,
      userId: localStorage.getItem("userId"),
      companyId: localStorage.getItem("companyId"),
      curPageUrl: window.location.href,
    }
    Object.assign(sorceData, data);
    ckjrRequest({
      method: 'post',
      url: `${global.apiurl}common/reportError`,
      data: sorceData,
    });
  },
  //关闭页面前发送数据
  berforeCloseSendData(url, data) {
    let postData = new FormData();
    for (let key in data) {
      postData.append(key, data[key]);
    }
    if (navigator.sendBeacon) {
      postData.append('postMethods', 'sendBeacon');
      navigator.sendBeacon(url, postData);
    } else {
      postData.append('postMethods', 'post');
      let client = new XMLHttpRequest();
      client.open("POST", url, false); // 第三个参数表明是同步的 xhr
      client.setRequestHeader('Content-Type', 'multipart/form-data');
      client.send(postData);
    }
  },
    // 获取小程序底部导航信息
  getWxAppNav() {
    return new Promise(function (resolve, reject) {
      utilJs.getMethod(global.apiurl + "common/getBottomNav?type=2", res => {
        localStorage.removeItem('wxAppNav');
        !!res && localStorage.setItem("wxAppNav", JSON.stringify(res));
        resolve(res);
      }, failRes => {
        localStorage.removeItem('wxAppNav');
        reject(failRes)
      })
    })
  },
  // 获取充值卡信息
  getGiftCardInfo(type = 0) {
    return new Promise(function (resolve, reject) {
      if (!type && !!localStorage.getItem('giftCardInfo') && !!JSON.parse(localStorage.getItem('giftCardInfo'))) {
        let giftCardInfo = JSON.parse(localStorage.getItem('giftCardInfo')) || {}
        resolve(giftCardInfo);
      } else {
        localStorage.removeItem('giftCardInfo');
        utilJs.getMethod(global.apiurl + "giftCard/getGiftCardBaseInfo", res => {
          let data = {
            coinImg: res.coinImg,
            name: res.name,
            status: res.status
          }
          !!res && localStorage.setItem("giftCardInfo", JSON.stringify(data)); // 虚拟币名称、图标等信息
          resolve(res);
        }, failRes => {
          reject(failRes)
        })
      }
    })
  },
  // 获取手机浏览器类型（目前只判断微信、抖音、快手以及其他手机浏览器）
  getMobileBrowserType() {
    if (!utilJs.isIOSAppALL() && !utilJs.isAndroidApp() && !this.isAndoridNewApp()) {
      let ua = window.navigator.userAgent.toLowerCase();
      if (utilJs.isMobileUserAgent()) {
        if (ua.match(/MicroMessenger/i) == 'micromessenger' && ua.match(/wxwork/i) != "wxwork" && localStorage.getItem("wxAppEnvironment") != 'wxwork') {
          return 'wx';
        } else if (ua.match(/MicroMessenger/i) == 'micromessenger' && (ua.match(/wxwork/i) == "wxwork" || localStorage.getItem("wxAppEnvironment") == 'wxwork')) {
          return 'qywx';
        } else if (!!ua.includes('aweme')) {
          return 'dy';
        } else if (!!ua.includes('kwai')) {
          return 'ks';
        } else {
          return 'llq';
        }
      } else {
        if (ua.match(/MicroMessenger/i) == 'micromessenger' && ua.match(/wxwork/i) != "wxwork" && localStorage.getItem("wxAppEnvironment") != 'wxwork') {
          return 'wx';
        } else if (ua.match(/MicroMessenger/i) == 'micromessenger' && (ua.match(/wxwork/i) == "wxwork" || localStorage.getItem("wxAppEnvironment") == 'wxwork')) {
          return 'qywx';
        } else {
          return 'pcwb';
        }
      }
    } else {
      return '';
    }
  },
  getCustNameMap(customObj = {}) {
    let companyAuth = localStorage.getItem("companyAuth") ? JSON.parse(localStorage.getItem("companyAuth")) : {};
    let customName = localStorage.getItem("customName") ? JSON.parse(localStorage.getItem("customName")) : {}
    let nameMap = {
      1: customObj[1] || '普通用户',
      2: 'VIP',
      4: customObj[4] || 'SVIP', // svip没开启或者svip没规格都不展示
      3: customName.agentName,
      5: companyAuth.agentLevels >= 2 ? customName.partnerName : '',
      6: companyAuth.agentLevels >= 3 ? customName.branchName : '',
      7: companyAuth.agentLevels >= 4 ? customName.cooName : '',
      8: companyAuth.agentLevels >= 5 ? customName.agencyName : '',
      9: companyAuth.agentLevels >= 6 ? customName.agent6Name : '',
      10: companyAuth.agentLevels >= 7 ? customName.agent7Name : '',
      11: companyAuth.agentLevels >= 8 ? customName.agent8Name : '',
      12: companyAuth.agentLevels >= 9 ? customName.agent9Name : ''
    }
    return nameMap
  },
  // 以下是小程序套壳相关函数
  getEnv: () => {
    return new Promise(function (resolve, reject) {
      var ua = navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == "micromessenger") {
        wx.miniProgram.getEnv((res) => {
          resolve(res.miniprogram ? 'wxApp' : 'gzh');
        });
      } else {
        resolve('qt');
      }
    });
  },
  miniProgramGoTo: (type, path, query) => {
    if (query && typeof query == 'object') {
      for (let key in query) {
        path += (path.indexOf('?') == -1 ? '?' : '&') + `${key}=${query[key]}`;
      }
    }
    if (type == "switchTab") {
      wx.miniProgram.switchTab({
        url: path
      })
    } else if (type == 'reLaunch') {
      wx.miniProgram.reLaunch({
        url: path
      })
    } else if (type == "replace") {
      wx.miniProgram.redirectTo({
        url: path
      })
    } else {
      wx.miniProgram.navigateTo({
        url: path
      })
    }
  },
  miniProgramBack() {
    wx.miniProgram.navigateBack()
  },
  miniProPostMsg: (data) => {
    wx.miniProgram.postMessage({data: data})
  },
  checkIsNativeInMiniPro: (data) => { // 检查是否要跳小程序页面
    let isIos = navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); // 是否是ios机型
    let currentPath = window.location.href; // 当前页面
    let nextPath = data.path; // 即将跳转的页面
    let goPath = ''
    let isSwitchTab = false
    let isForbid = false
    if (!localStorage.getItem("wxAppVersion") && nextPath == "/") {
      goPath = '/pages/home/index/index',
      isSwitchTab =  true
    } else if (!localStorage.getItem("wxAppVersion") || sessionStorage.getItem('isKpStudy')) {
      // 兼容旧版小程序（20230406之前的版本）
      let nataveInMiniProList = []; // web页面有对应要替换的原生页面
      if (!sessionStorage.getItem('isKpStudy')) {
        nataveInMiniProList = [
          {webPath: 'homePage/course/coursePay', nativePath: isIos ? "pages/member/contact/index" : "pages/member/orderPay/index"},
          {webPath: 'member/vip/vipUp', nativePath: 'pages/member/vipUp/index', isForbid: isIos ? true : false},
          {webPath: 'member/myValueVoucher/myValueVoucher', nativePath: 'pages/member/myValueVoucher/index'},
          {webPath: 'member/myOrder/allOrderList', nativePath: 'pages/member/orderList/index'},
          {webPath: 'member/memberIndex', nativePath: 'pages/member/index/index', isSwitchTab: true},
          {webPath: 'mall/mallIndex', nativePath: 'mall/pages/mallIndex/index'},
          {webPath: 'mall/shopDetail/shopDetail', nativePath: 'mall/pages/shopDetail/index'},
          {webPath: 'mall/shopSettlement/shopSettlement', nativePath: 'mall/pages/shopSettlement/index'},
          {webPath: 'mall/shippingAddress/addressList', nativePath: 'mall/pages/mallAdress/addressList/index'},
          // {webPath: 'homePage/login/bindMobile', nativePath: 'pages/member/bindPhone/index'},
          {webPath: 'homePage/circle/circleList', nativePath: 'pages/home/list/index?prodType=181'}
        ]
      } else {
        nataveInMiniProList = [
          {webPath: 'homePage/course/video', nativePath: 'pages/home/course/video/index'},
          {webPath: 'homePage/course/voice', nativePath: 'pages/home/course/audio/index'},
          {webPath: 'homePage/course/imgText', nativePath: 'pages/home/course/article/index'},
          {webPath: 'homePage/column/columnDetail', nativePath: 'pages/home/column/index'}
        ]
      }
      for (let i = 0; i < nataveInMiniProList.length; i++) {
        if (nextPath.includes(nataveInMiniProList[i].webPath)) {
          goPath = nextPath.replace(nataveInMiniProList[i].webPath, nataveInMiniProList[i].nativePath);
          if (data.query && typeof data.query == 'object') {
            for (let key in data.query) {
              goPath += (goPath.indexOf('?') == -1 ? '?' : '&') + `${key}=${data.query[key]}`;
            }
          }
          if (nataveInMiniProList[i].isSwitchTab) { // 是否是小程序导航栏的页面
            isSwitchTab = nataveInMiniProList[i].isSwitchTab;
          }
          if (nataveInMiniProList[i].isForbid) { // 是否禁止跳转，ios机型vip相关页面不允许跳转
            isForbid = nataveInMiniProList[i].isForbid
          }
          break;
        }
      }
    } else if (nextPath == "/") {
      // 判断即将跳转的是h5首页直接替换成小程序首页
      goPath = '/pages/tabWebview/index'
    } else if (currentPath && currentPath.includes('member/myInterest/interestIndex') && (nextPath.includes('homePage/column/columnDetail') || nextPath.includes('homePage/course/voice'))) {
      // 如果是个人中心-我的课程 要跳转专栏或音频，需要跳到原生
      let extId = nextPath.split('extId=')[1] ? nextPath.split('extId=')[1].split('&')[0] : -1
      let courseId = nextPath.split('courseId=')[1] ? nextPath.split('courseId=')[1].split('&')[0] : -1
      let paath = nextPath.includes('homePage/column/columnDetail') ?
        `/pages/home/column/index?extId=${extId}&c=${localStorage.getItem('companyId')}&u=${localStorage.getItem('userId')}&mobile=${localStorage.getItem('uMobile')}` :
        `/pages/home/course/audio/index?courseId=${courseId}&c=${localStorage.getItem('companyId')}&u=${localStorage.getItem('userId')}&mobile=${localStorage.getItem('uMobile')}`
      goPath = `/pages/home/goWxApp/index?appId=wx032bc58d1be3d3e2&path=${encodeURIComponent(JSON.stringify(paath))}`;
    } else if (nextPath == '/homePage/course/coursePay' && isIos) {
      // 判断即将跳转的是支付页 && ios，需要替换成咨询客服
      goPath = '/pages/member/contact/index'
    }
    return goPath ? {path: goPath, isNative: true, isForbid: isForbid, isSwitchTab: isSwitchTab} : null
  },
  checkIsWebInMiniProUrl: (data) => { // 检查是否是当前小程序允许的web页面
    let isInminiPro = true;
    let unAllowList = [];
    if (sessionStorage.getItem('isKpStudy')) {
      unAllowList = [
        'activity/', // 活动
        'auth/',
        'edu/', // 教务
        'homePage/agent/', // 服务商
        'homePage/booking/', // 预约
        // 'homePage/datum/', // 资料
        'homePage/distribution/', // 内容专区
        'homePage/ebooks/', // 电子书
        // 'homePage/clockIn/', //打卡
        'homePage/clockIn/', //打卡
        'homePage/newAreaAgent/', // 新版区域代理
        'homePage/report/', // 用户举报
        'homePage/reservation/', // 约课
        'homePage/shareholder/', // 股东
        'homePage/socialGroup/', // 社群
        'homePage/voting/', // 投票
        'homePage/word/', // 词典
        'member/giftCard/', // 虚拟币（充值页面和充值记录页面）
        'member/myActivity', // 我的活动
        'member/myBooking', // 我的预约
        'member/myReservation', // 我的约课
        'member/mySocial', // 我的社群
        'member/myVote', // 我的投票
        'member/myWord', // 我的词典
        'member/classmates/', // 我的同学
        'member/feedback/', // 反馈
        'member/recommend', // 推荐
        'member/taxationForm', // 报单系统
        'message/', // 消息
        'distribution=1', // 内容市场相关的也不允许
        'homePage/live/liveRoom', // 语音直播、ppt直播
        'homePage/agent/agentIndex?fromType=shareholder', // 股东申请页面
        'homePage/agent/promotedAccountIndex', // 子店铺招募页
        'isPromotedAccount=1', // 子账号推广微页面
      ]
    } else {
      unAllowList = [
        // 'activity/', // 活动
        'auth/',
        'edu/', // 教务
        // 'homePage/agent/', // 服务商
        // 'homePage/booking/', // 预约
        // 'homePage/datum/', // 资料
        'homePage/distribution/', // 内容专区
        // 'homePage/ebooks/', // 电子书
        // 'homePage/newAreaAgent/', // 新版区域代理
        'homePage/report/', // 用户举报
        // 'homePage/reservation/', // 约课
        'homePage/shareholder/', // 股东
        // 'homePage/socialGroup/', // 社群
        'homePage/voting/', // 投票
        'homePage/word/', // 词典
        'member/giftCard/', // 虚拟币（充值页面和充值记录页面）
        // 'member/myActivity', // 我的活动
        // 'member/myBooking', // 我的预约
        // 'member/myReservation', // 我的约课
        // 'member/mySocial', // 我的社群
        'member/myVote', // 我的投票
        'member/myWord', // 我的词典
        // 'member/classmates/', // 我的同学
        'member/feedback/', // 反馈
        'member/recommend', // 推荐
        'member/taxationForm', // 报单系统
        // 'message/', // 消息
        'distribution=1', // 内容市场相关的也不允许
        'homePage/live/liveRoom', // 语音直播、ppt直播
        'homePage/agent/agentIndex?fromType=shareholder', // 股东申请页面
        'homePage/agent/promotedAccountIndex', // 子店铺招募页
        'isPromotedAccount=1', // 子账号推广微页面
      ]
    }
    for (let i = 0; i < unAllowList.length; i++) {
      if (data.path.includes(unAllowList[i]) && !data.path.includes('homePage/agent/protocolInfo')) {
        isInminiPro = false;
        break;
      }
    }
    return isInminiPro;
  },
  checkIsWebInMiniPro: (data) => { // 非小程序有的模块页面就跳转缺省页
    let goPathData = data;
    let isTab = window.location.href.includes('isTab'); //当前页面是不是tab页面
    let isList = window.location.href.includes('isList'); //当前页面是不是List页面
    let isAllow = utilJs.checkIsWebInMiniProUrl(data); // 检查下一个页面是否是当前小程序允许的web页面
    let isNextTabPage = utilJs.checkIsTab(data); // 下一个页面是不是tab页面
    let isNextListPage = utilJs.checkIsList(data); // 下一个页面是不是列表页面
    // 当前是否是分类页面，一级分类，重定向后就没有带isTab，会导致后续跳转的页面全都走同一个tabWebview,所以走listwebview 或 webView的时候需要包含这种情况
    let isCourseCategory = window.location.href.includes('courseCategory')
     // 下一个页面是否是分类，分类页面会存在重定向的情况，会陷入死循环，需要排除当前页面是courseCategory并且下一个页面也是courseCategory的情况，重定向直接走h5内部跳转
    let isNextCourseCategory = !(window.location.href.includes('courseCategory') && data.path.includes('courseCategory'));
    let emptyPath = "/error/emptyPage?from=" + (!!data.query && !!data.query.webTime ? 'fromWxApp' : "wxApp") + "&info=该功能还在开发中，敬请期待";
    let emptyPage = {
      path: `/pages/${isTab ? 'tabWebview' : 'webView'}/index?webUrl=` + encodeURIComponent(`${window.location.href.split("#")[0]}#${emptyPath}`),
      isNative: true,
      isReplace: isTab ? true : false
    }
    let webviewPath = ''
    if (isNextTabPage && isAllow && isNextCourseCategory) {
      // 判断即将跳转的页面也是tab页面，就走tabWebview
      webviewPath = 'tabWebview'
    } else if ((isTab || isCourseCategory) && isNextListPage && isAllow && isNextCourseCategory) {
      // 判断当前是tab页面并且即将跳转的页面是list页面，就走listWebview，防止详情页支付时，回退找不到list页面
      webviewPath = 'listWebview'
    } else if ((isTab || isList || isCourseCategory) && isAllow && isNextCourseCategory) {
      // 当前页面是tab页面或list页面，需要跳转到webView页面，而不是停留在tabWebview或listWebview
      webviewPath = 'webView'
    }
    // 兼容旧版小程序（20230406前的小程序版本）
    if (window.location.href.includes('courseCategory') && !data.path.includes('courseCategory') && !localStorage.getItem("wxAppVersion")) {
      webviewPath = 'webView'
    }
    if (webviewPath) {
      // 将路由上的参数加入路径
      if (data.query && typeof data.query == 'object') {
        for (let key in data.query) {
          data.path += (data.path.indexOf('?') == -1 ? '?' : '&') + `${key}=${data.query[key]}`;
        }
      }
      goPathData = {
        path: `/pages/${webviewPath}/index?webUrl=` + encodeURIComponent(`${window.location.href.split("#")[0]}#${data.path}`),
        isNative: true,
        isReplace: webviewPath == 'tabWebview' ? true : false
      }
    }
    goPathData = isAllow ? goPathData : emptyPage;
    return goPathData;
  },
  // 检查即将跳转的路由是否是tab页面
  checkIsTab: (data) => {
    let isTabPage = false
    let path = data.path && data.path.split('?')[0]
    let tabList = {
      "/": 0,
      "/mall/mallIndex": 1,
      "/activity/activityIndex": 2,
      "/message/messageIndex": 3,
      "/member/memberIndex": 4,
      "/homePage/live/liveList": 5,
      "/homePage/clockIn/clockInList": 6,
      "/homePage/column/columnList": 7,
      "/homePage/examination/examinationList": 8,
      "/homePage/socialGroup/socialGroupList": 9,
      "/homePage/collage/collageList": 10,
      "/homePage/qa/answerLord": 12,
      "/homePage/reservation/reservationList": 13,
      "/homePage/word/wordList": 14,
      "/homePage/booking/bookingList": 15,
      "/homePage/mutuaTest/mutuaTestList": 16,
      "/homePage/voiceTest/voiceTestList": 17,
      "/homePage/package/packageList": 18,
      "/homePage/camp/campList": 19,
      "/homePage/datum/datumList": 20,
      "/homePage/privateClass/classList": 21,
      "/homePage/microPage/microPage": 22,
      "/edu/eduList": 23,
      "/edu/faceTeaching": 24,
      "/edu/courseManagment": 24,
      "/homePage/live/livePersonalList": 25,
      "/homePage/agent/promotedAccountList": 26,
      "/homePage/circle/circleList": 27,
      "/homePage/course/courseList": 40,
      "/homePage/testPaper/testList": 41,
      "/homePage/itemBank/questionList": 42,
      "/member/watchList/learnCenter": 43,
      "/homePage/course/courseCategory": 44,
      "/homePage/spread/spreadIndex": 45
    }
    let companyNav = localStorage.getItem("companyAuth") ? JSON.parse(localStorage.getItem("companyAuth")) : {}
    let navList = companyNav.companyNav ? companyNav.companyNav : []
    let navListNum = navList.map(i => String(i.navType))
    if (String(tabList[path]) && navListNum.includes(String(tabList[path]))) {
      isTabPage = true
    }
    console.log(navListNum, 'navListNum')
    console.log(tabList[path])
    return isTabPage
  },
  // 列表页
  checkIsList: (data) => {
    let isList = false
    let list = [
      "/activity/activityIndex",
      "/edu/eduList",
      "/homePage/camp/campList",
      "/homePage/clockIn/clockInList",
      "/homePage/column/columnList",
      "/homePage/examination/examinationList",
      "/homePage/package/packageList",
      "/homePage/qa/answerLord",
      "/homePage/qa/myQA",
      "/homePage/socialGroup/socialGroupList",
      "/mall/mallIndex",
      "/member/myActivity/myActivity",
      "/member/myBooking/myBookingList",
      "/member/myClockIn/myClockInList",
      "/member/myCollage/myCollageList",
      "/member/myExamination/myExamination",
      "/member/myInterest/interestIndex",
      "/member/myOrder/allOrderList",
      "/member/myLive/myLiveCourse",
      "/member/myReservation/reservationClassList",
      "/member/mySocial/mySocialGroup",
      "/member/watchList/learnCenter",
      "/member/watchList/watchList",
      "/member/recommend/recommendIndex",
      "/mall/classification/newAndHot",
      "/mall/classification/classificationAll",
      "/homePage/privateClass/classList",
      "/homePage/live/liveList",
      "/homePage/reservation/reservationList",
      "/homePage/mutuaTest/mutuaTestList",
      "/homePage/voiceTest/voiceTestList",
      "/homePage/booking/bookingList",
      "/homePage/course/courseList",
      "/homePage/datum/datumList",
      "/homePage/ebooks/ebooksList",
      "/homePage/distribution/distributionList",
      "/homePage/testPaper/testList",
      "/homePage/collage/collageList",
      "/homePage/bargain/bargainList",
      "/homePage/flashSales/flashSalesList",
      "/homePage/task/taskList",
      "/homePage/itemBank/questionList",
      "/homePage/word/wordList",
      "/homePage/course/courseForenotice",
      "/homePage/circle/circleList",
      "/homePage/live/livePersonalList",
      "/homePage/valueVoucher/list",
      "/homePage/search/searchList",
      "/homePage/course/catDetailList",
      "/homePage/course/courseCategory"
    ]
    for (let i = 0; i < list.length; i++) {
      if (data.path.includes(list[i])) {
        isList = true;
        break;
      }
    }
    return isList
  },
  checkWxApp() { // 判断是否是小程序环境
    if (!utilJs.isWeiXin()) {
      localStorage.removeItem('isWxApp')
      localStorage.removeItem('isWxAppIos')
      return
    }
    let ua = window.navigator.userAgent;
    let isH5WxApp = ua.toLowerCase().match(/miniprogram/i) == 'miniprogram';
    let isIosUa = ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    if (isH5WxApp) {
      localStorage.setItem('isWxApp', 1)
    } else {
      localStorage.removeItem('isWxApp')
    }
    if (isH5WxApp && isIosUa) {
    localStorage.setItem('isWxAppIos', 1)
    } else {
      localStorage.removeItem('isWxAppIos')
    }
    return isH5WxApp
  },
  getScreenRecordingSetting() { // 获取防录屏配置信息
    return new Promise(function (resolve, reject) {
      utilJs.getMethod(global.apiurl + "company/getScreenRecordingSetting", res => {
        resolve(res);
      }, failRes => {
        reject(failRes)
      })
    })
  },
  // 以上是小程序套壳相关函数
  // 判断字符串是否包含<script> 标签
  checkScriptStr(str) {
    if (!str) {
      return ''
    }
    const originStr = str;
    const lowerCaseStr = str.toLowerCase();
    lowerCaseStr.replace(/<script/g, (match, matchIndex) => {
      const matchStr = originStr.substr(matchIndex, 7)
      str = str.replace(matchStr, '< s c r i p t ')
    })
    return str
  },
  // 获取引导入群自动弹框记录
  getLeadSocialLog(prodType, prodId){
    return new Promise(function (resolve, reject) {
      utilJs.getMethod(`${global.apiurl}common/getLeadSocialLog?prodId=${prodId}&prodType=${prodType}`, res => {
        console.log(res.cTime,'ressssss')
        resolve( res.cTime);
      }, failRes => {
        reject(failRes)
      })
    })
  },
  // 记录引导入群主动弹框
  saveLeadSocialLog(prodType, prodId){
    return new Promise(function (resolve, reject) {
      utilJs.postMethod(`${global.apiurl}common/saveLeadSocialLog`, {prodType: prodType ,prodId: prodId}, res => {
        console.log(res,'ressssss')
        resolve(res);
      }, failRes => {
        reject(failRes)
      })
    })
  },
  // 检查当前是否是中文价格，如免费、加密、指定用户等
  checkCnPrice(payType, price, prodType) {
    let isCnPrice = false
    // 1免费 || （2付费但价格为0 == 免费）|| 3加密 || 5指定购买 || 6指定学员 || (4 && (privateClass审核参与 || circle配套课程)) ||( 活动免费)
    if (payType == 1 || (payType == 2 && price == 0) || payType == 3 || payType == 5 || payType == 6
        || (payType == 4 && (prodType == global.ckFrom.privateClass || prodType == global.ckFrom.circle))
        || prodType == global.ckFrom.activity && price.split('~')[0] == price.split('~')[1] && Number(price.split('~')[0]) == 0) {
      isCnPrice = true
    }
    return isCnPrice
  },
    /**
     * @description:获取不同身份价格信息
     * @param {Object} data
     * {
     *    initPrice: 初始价格 - required
     *    optimal：最优价格数据结构
     *    collage：拼团数据
     *    bargain：砍价数据
     *    comonProdInfo: Object,
     *    chainInfo: Object, 链动商品数据
     *    vipDiscountType：1-折扣  2-价格
     *    vipDiscount：vip折扣
     *    vipDiscountPrice：vip价格
     *    svipDiscount：svip折扣
     *    svipDiscountPrice： svip价格
     * }
     * @returns {Object} res
     * {
     *    initPrice: 默认的价格（原始的价格）- required
     *    price: 最优的价格（最终的价格）- required
     *    tag：最优的价格的标签（是身份、链动、拼团、限时购) - required
     *    identity:{price:80, tag:'VIP'}
     *    chain：{price:100, tag:'链动价格'}
     *    activity：{price:100, tag:'发起拼团'}
     * }
     * @调用用方式
     *  //只获取最优价格
     *  utilJs.getPriceInfo({optimal});
     *  //获取最优价格（包含链动价格）
     *  utilJs.getPriceInfo({optimal,chainInfo});
     *  //获取最优价格（包含活动价格-什么活动关联什么数据collage、bargain）
     *  utilJs.getPriceInfo({optimal,collage});
     *  //获取最优价格（包含链动价格、身份价格、活动价格）
     *  utilJs.getPriceInfo({optimal,initPrice,collage,vipDiscountType,vipDiscount,vipDiscountPrice,svipDiscount,svipDiscountPrice});
     *  //获取最优价格-没有optimal（包含链动价格、身份价格、活动价格）
     *  utilJs.getPriceInfo({initPrice,collage,vipDiscountType,vipDiscount,vipDiscountPrice,svipDiscount,svipDiscountPrice});
     */
  getPriceInfo(data) {
    const optimal = data.optimal;
    const initPrice = data.initPrice;
    const collage = data.collage;
    const bargain = data.bargain;
    const commonProdInfo = data.commonProdInfo;
    const chainInfo = data.chainInfo;
    let vipStorageKey = 'vipType' + localStorage.getItem("userId");
    let vipType = localStorage.getItem(vipStorageKey);
    let vipDiscountType = data.vipDiscountType;
    let vipDiscount = data.vipDiscount;
    let vipDiscountPrice = data.svipDiscountPrice;
    let svipDiscount = data.svipDiscount;
    let svipDiscountPrice = data.svipDiscountPrice;
    let agentDiscount = 100;
    let res = {
      initPrice: initPrice,
      price: initPrice,
      tag:''
    }
    if (commonProdInfo) {
      agentDiscount = commonProdInfo.agentDiscount;
      vipDiscountType = commonProdInfo.vipDiscountType
    }
    // 身份价格计算
    if (vipType == 2 ) {
      // vip身份
      if (vipDiscountType == 1) {
        // 折扣
        if (vipDiscount && vipDiscount != 100) {
          res.identity = {
            price:(initPrice * vipDiscount / 100).toFixed(2),
            tag:"VIP"
          }
        }
      } else {
        // 价格
        if (vipDiscountPrice) {
          res.identity = {
            price:vipDiscountPrice * 1,
            tag:"VIP"
          }
        }
      }
    } else if (vipType == 4) {
      // svip 身份
      if (vipDiscountType == 1) {
        // 折扣
        if (svipDiscount && svipDiscount != 100) {
          res.identity = {
            price:(initPrice * svipDiscount / 100).toFixed(2),
            tag:"SVIP"
          }
        }
      } else {
        // 价格
        if (svipDiscountPrice) {
          res.identity = {
            price:svipDiscountPrice,
            tag:"SVIP"
          }
        }
      }
    } else if (vipType == 3 || vipType > 4) {
      // 服务商身份
      if (agentDiscount && agentDiscount != 100) {
        const agentName = utilJs.getCustNameMap();
        res.identity = {
          price:(initPrice * agentDiscount / 100).toFixed(2),
          tag:agentName[vipType],
        }
      }
    }
    // 链动价格计算
    if (chainInfo && chainInfo.isChainProd) {
      //链动商品，重新计算链动价
      if (chainInfo.isReorder) {
        //复购
        if (chainInfo.enableReorderDiscount == 1 && chainInfo.reorderBonus * 1 > 0) {
          //允许优惠&价格不为0
          res.chain = {
            price:chainInfo.reorderBonus,
            tag:"复购"
          }
        } else if (chainInfo.enableOrderDiscount == 1 && chainInfo.orderBonus * 1 > 0) {
          //复购，有下单优惠（不是复购优惠，类似第一次购买）
          res.chain = {
            price:chainInfo.orderBonus,
            tag:"复购"
          }
        }
      } else {
        //第一购买
        if (chainInfo.enableOrderDiscount == 1 && chainInfo.orderBonus * 1 > 0) {
          //允许优惠&价格不为0
          res.chain = {
            price:chainInfo.orderBonus,
            tag:chainInfo.userType == 1 ? '普通用户' : chainInfo.userType2Name[chainInfo.userType]
          }
        }
      }
    }
    // 活动价格
    if (collage && (collage.status == 2 || collage.status == 1)) {
      res.price = Number(collage.captainPrice).toFixed(2);
      res.activity = {
        price:collage.captainPrice,
        tag:collage.userType == -1 ? "发起拼团" : '拼团中...'
      }
    } else if (bargain && ((bargain.status == 1 && bargain.isPreheat == 1) || bargain.status == 2)) {
      res.price = Number(collage.captainPrice).toFixed(2);
      res.activity = {
        price: bargain.reservePrice,
        tag: bargain.userType == 1 ? '正在砍价' : '砍价享'
      }
    }
    // 新数据结构新增了optimal(最优价格计算)
    if(optimal){
      const {optimalPrice,optimalPriceType} = optimal;
      res.price = optimalPrice;
      res.optimalPriceType = optimalPriceType;
      // * optimalPriceType：1 产品本身价格 2 vip价格 3 svip价格 4 服务商 101 限时购 102 拼团 112 砍价  10 链动会员 20 链动代理商 99 链动复购
      switch(optimalPriceType){
        case 2:
          res.identity = {
            price:optimalPrice,
            tag:"VIP",
            isBest:1
          }
          break;
        case 3:
          res.identity = {
            price:optimalPrice,
            tag:"SVIP",
            isBest:1
          }
          break;
        case 4:
          res.identity = {
            price:optimalPrice,
            tag:"服务商",
            isBest:1
          } 
          break;
        case 10:
          res.chain = {
            price:optimalPrice,
            tag:"链动会员",
            isBest:1
          } 
          break;
        case 20:
          res.chain = {
            price:optimalPrice,
            tag:"链动代理商",
            isBest:1
          } 
          break;
        case 99:
          res.chain = {
            price:optimalPrice,
            tag:"链动复购",
            isBest:1
          } 
          break;
        case 101:
          res.activity = {
            price:optimalPrice,
            tag:"限时购",
            isBest:1
          } 
          break;
        case 102:
          res.activity = {
            price:optimalPrice,
            tag: collage && collage.userType == 1 ? '拼团中...': '发起拼团',
            isBest:1
          } 
          break;
        case 112:
          res.activity = {
            price:optimalPrice,
            tag:bargain && bargain.userType == 1 ? '正在砍价' : '砍价享',
            isBest:1
          }
          break;
        default:
          res.price = optimalPrice;
      }
      for(let k in res){
        if (Object.prototype.toString.call(res[k]) == '[object Object]' && res[k].isBest) {
          res.tag = res[k].tag
        }
      }
      console.log("getPriceInfo-新数据：", res, optimal);
    } else {
      // 旧数据计算最优的价格
      if (typeof res.chain != 'undefined' && (typeof res.identity === 'undefined' || res.chain.price <= res.identity.price) && (typeof res.activity === 'undefined' || res.chain.price <= res.activity.price)) {
        res.chain.isBest = 1;
        res.price = res.chain.price;
        res.tag = res.chain.tag;
      } else if (typeof res.identity != 'undefined' && (typeof res.chain === 'undefined' || res.identity.price <= res.chain.price) && (typeof res.activity === 'undefined' || res.identity.price <= res.activity.price)) {
        res.identity.isBest = 1;
        res.price = res.identity.price;
        res.tag = res.identity.tag;
      } else if (typeof res.activity != 'undefined' && (typeof res.identityPrice === 'undefined' || res.activityPrice <= res.identityPrice) && (typeof res.chainPrice === 'undefined' || res.activityPrice <= res.chainPrice)) {
        res.activity.isBest = 1;
        res.price = res.activity.price;
        res.tag = res.activity.tag;
      }
      console.log("getPriceInfo-旧数据：", res, optimal);
    }
    return res;
  },
  base64ToFile(base64, fileName, fileType){
    return new Promise((resolve) => {
      const binaryString = atob(base64.split(',')[1]);
      const len = binaryString.length;
      const bytes = new Uint8Array(len);
      for (let i = 0; i < len; i++) {
        bytes[i] = binaryString.charCodeAt(i);
      }
      const blob = new Blob([bytes], { type: fileType });
      const file = new File([blob], fileName, { type: fileType });
      resolve(file);
    });
  },
  getRandomString(len){
    // 获取随机字符串
    len = len || 32;
    const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    const maxPos = chars.length;
    let pwd = '';
    for (let i = 0; i < len; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  },
  /**
   * 获取文件信息，包括时长、宽度和高度。
   *
   * @param {File | string} file - 文件对象或文件的线上地址。
   * @param {Number} [fileType] - 2是否为视频文件，默认为音频文件。
   * @param {Object} [params] - 其他参数
   * @returns {Promise<GetFileInfoRes>} - 返回一个 Promise，解析为包含文件信息的对象。
   * @throws {Error} - 如果获取文件时长失败，将抛出错误。
   */
  getFileInfo(file, fileType = 1, params = {}){
    return new Promise((resolve, reject) => {
      let fileUrl = '';
      if (typeof file === 'string') {
        //线上地址
        fileUrl = file;
      } else {
        //本地file文件
        fileUrl = URL.createObjectURL(file);
      }
      const destoryDom = () => {
        // 释放URL对象
        URL.revokeObjectURL(fileUrl);
        // 移除事件监听器
        dom.onloadedmetadata = null;
        dom.onerror = null;
        dom = null;
      };
      let dom = null;
      if (fileType == 2) {
        dom = document.createElement('video');
        dom.crossOrigin = 'anonymous';
      } else {
        dom = document.createElement('audio');
      }
      dom.src = fileUrl;
      dom.muted = true;
      dom.onloadedmetadata = async () => {
        let coverUrl = '';
        if (fileType == 2) {
          coverUrl = await this.captureFirstFrame(dom);
          let fileName = 'videologo' + this.getRandomString();
          let file = await this.base64ToFile(coverUrl, fileName, "image/jpeg");
          console.log(file, fileName);
          let res= await this.uploadImgListToOss([file],{...params});
          resolve({
            duration: Math.round(dom.duration),
            width: dom?.videoWidth,
            height: dom?.videoHeight,
            cover: coverUrl,
            videoLogo: res[0]
          });
        } else {
          resolve({
            duration: Math.round(dom.duration),
            width: dom?.videoWidth,
            height: dom?.videoHeight,
            cover: coverUrl
          });
          destoryDom();
        }
      };
      dom.onerror = (err) => {
        AiMessage.warning('获取文件时长失败');
        reject(err);
        destoryDom();
      };
      dom.load();
    });
  },
  /**
   * 获取视频封面首帧
   * @param videoElement 视频元素
   * @returns
   */
  captureFirstFrame(videoElement){
    return new Promise((resolve, reject) => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      if (!ctx) {
        reject(new Error('无法获取画布上下文'));
        return;
      }
      const videoWidth = videoElement.videoWidth;
      const videoHeight = videoElement.videoHeight;
      canvas.width = videoWidth;
      canvas.height = videoHeight;
      videoElement.addEventListener('seeked', () => {
        ctx.drawImage(videoElement, 0, 0, videoWidth, videoHeight);
        const imageData = canvas.toDataURL('image/jpeg');
        resolve(imageData);
      });
      videoElement.currentTime = 0.1;
    });
  },
  /**
   * 获取授权相关配置信息
   * @returns 
   */
  getLiveAuthData() {
    if (global.liveAuthData) {
      return Promise.resolve(global.liveAuthData);
    }
    return new Promise(resolve => {
      utilJs.getMethod(`${global.apiurl}common/getLiveAuthData`, res => {
        global.liveAuthData = res;
        resolve(res);
      });
    });
  },

  /**
   * 获取门店权限
   * @returns
   */
  getStorePermission(){
    return new Promise((resolve,reject) => {
      this.getMethod(`${global.apiurl}multiStore/getVisitPermission`, res => {
        // res.isStoreVisit = 0;
        resolve(res)
      },()=>{
        reject();
      })
    })
  },
  getVideoSign(module = ''){
    return ckjrRequest({url:`${global.apiurl}signCard/getVideoSign?companyId=${localStorage.getItem("companyId")}&type=${module}`}).then((response) => {
        return response.data.data;
      });;
  }
}

//判断访问终端
var browser = {
  versions: (function () {
    var u = navigator.userAgent;
    return {
      trident: u.indexOf('Trident') > -1, //IE内核
      presto: u.indexOf('Presto') > -1, //opera内核
      webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
      gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
      mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
      ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
      android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
      iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
      iPad: u.indexOf('iPad') > -1, //是否iPad
      webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
      weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
      qq: u.match(/\sQQ/i) == " qq" //是否QQ
    };
  })(),
  language: (navigator.browserLanguage || navigator.language).toLowerCase()
}

var wxUtilJs = {
  initConfig: (shareData, hideMenu) => {
    return new Promise(function (resolve, reject) {
      let jsApiList = [
        "onMenuShareTimeline",
        "onMenuShareAppMessage",
        "onMenuShareQQ",
        "onMenuShareWeibo",
        "onMenuShareQZone",
        "startRecord",
        "stopRecord",
        "onVoiceRecordEnd",
        "playVoice",
        "pauseVoice",
        "stopVoice",
        "onVoicePlayEnd",
        "uploadVoice",
        "downloadVoice",
        "chooseImage",
        "previewImage",
        "uploadImage",
        "downloadImage",
        "chooseWXPay",
        "hideMenuItems",
        "openLocation",
        "getLocation",
        "openAddress",
        "showAllNonBaseMenuItem",
        "openBusinessView"
      ];

      let url = checkApiHp(global.apiurl + 'mp/jsConfig');
      ckjrRequest({
        method: 'post',
        url: url,
        data: {
          jsApiList: jsApiList,
          url: navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) ? localStorage.getItem('firstPage') : window.location.href
        },
      }).then(res => {
        let data = res.data.data;
        let configData = {
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: data.appId, // 必填，公众号的唯一标识
          timestamp: data.timestamp, // 必填，生成签名的时间戳
          nonceStr: data.nonceStr, // 必填，生成签名的随机串
          signature: data.signature, // 必填，签名
          jsApiList: data.jsApiList // 必填，需要使用的JS接口列表
        }
        wx.config(configData);
        wx.ready(() => {
          wx.onMenuShareAppMessage({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            title: shareData.title, // 分享标题
            desc: shareData.desc,
            link: shareData.link,
            imgUrl: shareData.imgUrl,
            success: function () {
              // 用户确认分享后执行的回调函数
              resolve('onMenuShareAppMessageSuccess');
            },
            cancel: function () {
              // 用户取消分享后执行的回调函数
              resolve('onMenuShareAppMessageCancel');
            }
          });
          wx.onMenuShareTimeline({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            title: shareData.title, // 分享标题
            desc: shareData.desc,
            link: shareData.link,
            imgUrl: shareData.imgUrl,
            success: function () {
              // 用户确认分享后执行的回调函数
              resolve('onMenuShareTimelineSuccess');
            },
            cancel: function () {
              // 用户取消分享后执行的回调函数
              resolve('onMenuShareTimelineCancel');
            }
          });
          wx.onMenuShareQQ({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            title: shareData.title, // 分享标题
            desc: shareData.desc,
            link: shareData.link,
            imgUrl: shareData.imgUrl,
            success: function () {
              // 用户确认分享后执行的回调函数
              resolve('onMenuShareQQSuccess');
            },
            cancel: function () {
              // 用户取消分享后执行的回调函数
              resolve('onMenuShareQQCancel');
            }
          });
          wx.onMenuShareQZone({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            title: shareData.title, // 分享标题
            desc: shareData.desc,
            link: shareData.link,
            imgUrl: shareData.imgUrl,
            success: function () {
              // 用户确认分享后执行的回调函数
              resolve('onMenuShareQZoneSuccess');
            },
            cancel: function () {
              // 用户取消分享后执行的回调函数
              resolve('onMenuShareQZoneCancel');
            }
          });
          if (hideMenu) {
            wx.hideMenuItems({
              menuList: [
                'menuItem:share:qq',
                'menuItem:copyUrl',
                'menuItem:openWithSafari',
                'menuItem:originPage',
                'menuItem:share:email',
                'menuItem:share:brand'
              ]
              // 要隐藏的菜单项，所有menu项见附录3
            });
          } else {
            wx.showAllNonBaseMenuItem();
          }
        });
        // wx.config({
        //   debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        //   appId: data.appId, // 必填，公众号的唯一标识
        //   timestamp: data.timestamp, // 必填，生成签名的时间戳
        //   nonceStr: data.nonceStr, // 必填，生成签名的随机串
        //   signature: data.signature, // 必填，签名
        //   jsApiList: data.jsApiList // 必填，需要使用的JS接口列表
        // })
        // resolve();
      }).catch(function (error) {
        console.log(error);
      });
    })
  },
  //选择图片
  chooseImage: (data) => {
    return new Promise(function (resolve, reject) {
      let sorceData = {
        count: 1, // 默认9
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      };
      Object.assign(sorceData, data);
      setTimeout(() => {
        wx.chooseImage({
          count: sorceData.count, // 默认9
          sizeType: sorceData.sizeType, // 可以指定是原图还是压缩图，默认二者都有
          sourceType: sorceData.sourceType, // 可以指定来源是相册还是相机，默认二者都有
          success: function (res) {
            var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
            resolve(localIds);
          },
          fail: function (res) {
            reject();
            let errorData = {
              uA: navigator.userAgent,
              res: JSON.stringify(res),
              userId: localStorage.getItem("userId"),
              companyId: localStorage.getItem("companyId"),
              type: 'wx.chooseImage',
              curUrl: window.location.href,
            }
            utilJs.reprotError(errorData);
          }
        });
      }, 310);
    
    });
  },
  //预览图片
  previewImage: (data) => {
    //放大图片不使用压缩图
    let newCurSrc = data.current.split('?x-oss-process=style/w800')[0];
    data.current = newCurSrc;
    for(let i=0;i<data.urls.length;i++){
      let item = data.urls[i].split('?x-oss-process=style/w800')[0];
      data.urls[i] = item;
    }
    if (utilJs.isWeiXin() && utilJs.isMobileUserAgent()) {
      wx.previewImage({
        current: data.current, // 当前显示图片的http链接
        urls: data.urls // 需要预览的图片http链接列表
      });
    } else {
      let index = data.urls.indexOf(data.current) > -1 ? data.urls.indexOf(data.current) : 0;
      // viewBigPicture.viewPicture(data.urls, index);
      Vue.prototype.$previewImg({
        activeIndex: index,
        imgList: data.urls
      })
    }
  },
  //上传图片
  uploadImage: (data, showProgressTips) => {
    return new Promise(function (resolve, reject) {
      wx.uploadImage({
        localId: data.localId, // 需要上传的图片的本地ID，由chooseImage接口获得
        isShowProgressTips: showProgressTips ? 1 : 1, // 默认为1，显示进度提示
        success: function (res) {
          var serverId = res.serverId; // 返回图片的服务器端ID
          resolve(serverId);
        },
        fail: function (res) {
          reject(res)
          let errorData = {
            uA: navigator.userAgent,
            res: JSON.stringify(res),
            userId: localStorage.getItem("userId"),
            companyId: localStorage.getItem("companyId"),
            type: 'wx.uploadImage',
            curUrl: window.location.href,
          }
          utilJs.reprotError(errorData);
        }
      });
    });
  },
  //下载图片
  downloadImage: (data) => {
    return new Promise(function (resolve, reject) {
      wx.downloadImage({
        serverId: data.serverId, // 需要下载的图片的服务器端ID，由uploadImage接口获得
        isShowProgressTips: 1, // 默认为1，显示进度提示
        success: function (res) {
          var localId = res.localId; // 返回图片下载后的本地ID
          resolve(localId);
        }
      });
    });
  },
  //开始录音
  startRecord: () => {
    return new Promise(function (resolve, reject) {
      wx.startRecord({
        success: function (res) {
          resolve(res);
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },

  //停止录音
  stopRecord: () => {
    return new Promise(function (resolve, reject) {
      wx.stopRecord({
        success: function (res) {
          var localId = res.localId;
          resolve(localId);
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
  //录音自动停止
  onVoiceRecordEnd: () => {
    return new Promise(function (resolve, reject) {
      wx.onVoiceRecordEnd({
        // 录音时间超过一分钟没有停止的时候会执行 complete 回调
        complete: function (res) {
          var localId = res.localId;
          resolve(localId);
        }
      });
    });
  },
  //上传语音
  uploadVoice: (data, showProgressTips) => {
    return new Promise(function (resolve, reject) {
      wx.uploadVoice({
        localId: data.localId, // 需要上传的音频的本地ID，由stopRecord接口获得
        isShowProgressTips: showProgressTips ? 0 : 1, // 默认为1，显示进度提示
        success: function (res) {
          var serverId = res.serverId; // 返回音频的服务器端ID
          resolve(serverId);
        },
        fail: function (res) {
          reject(res)
          let errorData = {
            uA: navigator.userAgent,
            res: JSON.stringify(res),
            uploadData: JSON.stringify(data),
            userId: localStorage.getItem("userId"),
            companyId: localStorage.getItem("companyId"),
            type: 'wx.uploadVoice',
            curUrl: window.location.href,
          }
          utilJs.reprotError(errorData);
        }
      });
    });
  },
  //下载语音
  downloadVoice: (data) => {
    return new Promise(function (resolve, reject) {
      wx.downloadVoice({
        serverId: data.serverId, // 需要上传的音频的本地ID，由stopRecord接口获得
        isShowProgressTips: 0, // 默认为1，显示进度提示
        success: function (res) {
          var localId = res.localId; // 返回音频的服务器端ID
          resolve(localId);
        }
      });
    });
  },
  //播放语音
  playVoice: (data) => {
    return new Promise(function (resolve, reject) {
      wx.playVoice({
        localId: data.localId, // 需要上传的音频的本地ID，由stopRecord接口获得
      });
    });
  },
  //停止播放语音
  stopVoice: (data) => {
    return new Promise(function (resolve, reject) {
      wx.stopVoice({
        localId: data.localId, // 需要上传的音频的本地ID，由stopRecord接口获得
      });
    });
  },
  //监听语音播放完毕
  onVoicePlayEnd: (callBack) => {
    wx.ready(() => {
      wx.onVoicePlayEnd({
        success: function (res) {
          console.log('onVoicePlayEndwxcallBack.onVoicePlayEnd :ID=' + res.localId)
          var localId = res.localId; // 返回音频的本地ID
          callBack(localId)
        }
      });
    });
  },
  //获取网络状态接口
  getNetworkType: () => {
    return new Promise(function (resolve, reject) {
      wx.getNetworkType({
        success: function (res) {
          resolve(res.networkType)
        }
      });
    });
  },
  //打开地图
  openLocation: (data) => {
    return new Promise(function (resolve, reject) {
      wx.openLocation({
        latitude: data.latitude, // 纬度，浮点数，范围为90 ~ -90
        longitude: data.longitude, // 经度，浮点数，范围为180 ~ -180。
        name: data.name, // 位置名
        address: data.address, // 地址详情说明
        scale: data.scale, // 地图缩放级别,整形值,范围从1~28。默认为最大
        infoUrl: data.infoUrl // 在查看位置界面底部显示的超链接,可点击跳转
      });
    });
  },
  //获取地理位置
  getLocation: () => {
    return new Promise(function (resolve, reject) {
      wx.getLocation({
        type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
        success: function (res) {
          resolve(res)
          // var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
          // var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
          // var speed = res.speed; // 速度，以米/每秒计
          // var accuracy = res.accuracy; // 位置精度
        },
        cancel: function (res) {
          reject(res)
        },
        fail: function (res) {
          reject(res)
        },
      });
    });
  },
  openAddress: ()=>{
    return new Promise(function (resolve, reject) {
      wx.openAddress({
        success: function (res) {
          resolve(res)
        },
        cancel: function (res) {
          reject(res)
        },
        fail: function (res) {
          reject(res)
        },
      });
    });
  },
  //批量隐藏功能按钮接口
  hideMenuItems: (res, hideData) => {
    return new Promise(function (resolve, reject) {
      wx.config(res);
      wx.ready(() => {
        wx.hideMenuItems({
          menuList: hideData
        });
        wx.showMenuItems({
          menuList: ['menuItem:openWithQQBrowser', 'menuItem:openWithSafari'] // 要显示的菜单项，所有menu项见附录3
        });
      });
    });
  },

  //微信支付
  chooseWXPay: (data) => {
    return new Promise(function (resolve, reject) {
      wx.chooseWXPay({
        timestamp: data.timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
        nonceStr: data.nonceStr, // 支付签名随机串，不长于 32 位
        package: data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
        signType: data.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
        paySign: data.paySign, // 支付签名
        success: function (res) {
          // 支付成功后的回调函数
          resolve(res);
        }
      });
    });
  }
}



export {
  deviceUtil,
  wx,
  browser,
  utilJs,
  wxUtilJs
}
